﻿using ILRuntime.Runtime.Debugger.Protocol;
using Microsoft.Diagnostics.Runtime.DacInterface;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ETModel
{
    public class Command
    {
        private static bool orderAddress = false;

        public static async System.Threading.Tasks.Task OrderAsync(HttpMessage httpMessage)
        {
            
            Wallet.Inst = null;
            if (httpMessage.map["0"] == "importkey")
            {
                if (!GetParam(httpMessage, "1", "1", out string privatekey))
                {
                    httpMessage.result = "command error! \nexample: import key privatekey";
                    return;
                }
                string address = AddKeyBag(privatekey, Program.keyBag);
                httpMessage.result = $" {address}";
            }
            else if (httpMessage.map["0"] == "showip")
            {
                httpMessage.result = JsonHelper.ToJson(Program.ruleIP);
            }
            else if (httpMessage.map["0"] == "openwallet")
            {
                Wallet wallet = new Wallet();
                if (httpMessage.map.Count == 2)
                {
                    httpMessage.map.Add("1", "./smartx-wallet.json");
                }
                if (Program.wallet.keys.Count > 0)
                {
                    httpMessage.result = "please close wallet first!";
                    return;
                }
                try
                {
                    string path = httpMessage.map["1"];
                    Wallet wallet1 = Wallet.GetWallet(path);
                    wallet = wallet1;
                }
                catch (Exception e)
                {
                    httpMessage.result = "Please check your path";
                    return;
                }


                if (wallet == null)
                {
                    httpMessage.result = "Password error";
                    return;
                }
                if (Program.keyBag.Count > 0)
                {
                    if (!Program.keyBag.ContainsKey(wallet.keys[0].ToAddress()))
                    {
                        Program.keyBag.Add(Wallet.ToAddress(wallet.keys[0].publickey), wallet.keys[0]);
                    }
                }
                else
                {
                    Program.keyBag.Add(Wallet.ToAddress(wallet.keys[0].publickey), wallet.keys[0]);
                }
                Program.wallet = wallet;
                //string random = Program.wallet.keys[0].random.ToHex();
                //string nonce="0";
                string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);//0
                if (nonce == "INVALID URL, set the correct url" || nonce == "false")
                {
                    httpMessage.result = nonce;
                    Wallet.Inst = null;
                    Program.wallet = new Wallet();
                    Program.nonce = "";

                    return;
                }
                Program.nonce = (int.Parse(nonce) + 1).ToString();
                //Console.WriteLine(Program.nonce);
                httpMessage.result = Wallet.ToAddress(Program.wallet.keys[0].publickey) + " open";
            }
            else if (httpMessage.map["0"] == "setwallet")
            {
                if (!GetParam(httpMessage, "1", "address", out string address))
                {
                    httpMessage.result = "command error! \nexample: setwallet address";
                    return;
                }
                WalletKey key = new WalletKey();
                if (Program.keyBag.Count > 0)
                {
                    if (Program.keyBag.ContainsKey(address))
                    {
                        key = Program.keyBag[address];
                    }
                    else
                    {
                        httpMessage.result = "The address isn't in the key bag";
                        return;
                    }
                }
                else
                {
                    httpMessage.result = "The address isn't in the key bag";
                    return;
                }

                if (Program.wallet.keys.Count != 0)
                {
                    httpMessage.result = "please close wallet first!";
                    return;
                }
                Program.wallet.keys.Add(key);
                string nonce = await GetNonceAsync(address, httpMessage, Program.ruleIP);//0
                if (nonce == "INVALID URL, set the correct url" || nonce == "false")
                {
                    httpMessage.result = nonce;
                    return;
                }
                Program.nonce = (int.Parse(nonce) + 1).ToString();
                httpMessage.result = $"{address} set";
            }
            else if (httpMessage.map["0"] == "list")
            {
                List<string> list = new List<string>();
                foreach (KeyValuePair<string, WalletKey> k in Program.keyBag)
                {
                    list.Add(k.Key);
                }
                httpMessage.result = JsonHelper.ToJson(list);
            }
            else if (httpMessage.map["0"] == "closewallet")
            {
                Wallet.Inst = null;
                Program.wallet = new Wallet();
                Program.nonce = "";
                httpMessage.result = "wallet closed";
            }
            else if (httpMessage.map["0"] == "getprivatekey")
            {
                if (Program.wallet.keys.Count != 0)
                {
                    httpMessage.result = JsonHelper.ToJson(Program.wallet.keys[0].random.ToHexString());
                }
                else
                {
                    httpMessage.result = "please set wallet";
                }
            }
            else if (httpMessage.map["0"] == "exportkey")
            {
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "please set wallet";
                    return;
                }
                if (httpMessage.map.Count <= 2)
                {
                    File.WriteAllText("./private.json", Program.wallet.keys[0].random.ToHexString());
                    httpMessage.result = $"export key  successful";
                    return;
                }
                else if (Program.wallet.keys.Count > 0)
                {
                    try
                    {
                        File.WriteAllText(httpMessage.map["1"] + "/private.json", Program.wallet.keys[0].random.ToHexString());
                        httpMessage.result = $"export key  successful";
                    }
                    catch (Exception)
                    {
                        httpMessage.result = "Please check the path";
                        return;
                    }
                }
                else
                {
                    httpMessage.result = "Please set the wallet first";
                }
            }
            else if (httpMessage.map["0"] == "clear")
            {
                Console.Clear();
            }
            else if (httpMessage.map["0"] == "transfer")
            {
                await OnTransferAsync(httpMessage);
                return;
            }
            else if (httpMessage.map["0"] == "tokentransfer")
            {
                if (httpMessage.map.Count <= 4)
                {
                    Console.WriteLine("tokentransfer error example tokentransfer addressOut amount conAddress");
                    return;
                }
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                if (!Wallet.CheckAddress(httpMessage.map["1"]))
                {
                    httpMessage.result = "Please check addressOut";
                    return;
                }
                if (!Wallet.CheckAddress(httpMessage.map["3"]))
                {
                    httpMessage.result = "Please check conAddress";
                    return;
                }
                if (!Wallet.CheckAddress(httpMessage.map["1"]))
                {
                    httpMessage.result = "Please check addressOut";
                    return;
                }
                TransferInfo_Token(httpMessage, Program.ruleIP);
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                if (result.result.Contains("true"))
                {
                    Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                    httpMessage.result = result.result + " " + httpMessage.map["hash"];
                }
                else
                {
                    httpMessage.result = "false";
                }

            }
            else if (httpMessage.map["0"] == "createkey")
            {
                Console.WriteLine("Please enter random word: ");
                string input = Console.ReadLine();
                WalletKey walletKey = new WalletKey();
                walletKey.random = CryptoHelper.Sha256(Seek().ToHexString() + "#" + input).HexToBytes();
                ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, walletKey.random);
                if (walletKey.random != null)
                {
                    Dictionary<string, string> walletinfo = new Dictionary<string, string>();
                    walletinfo.Add("address", walletKey.ToAddress());
                    walletinfo.Add("privatekey", walletKey.random.ToHexString());
                    httpMessage.result = JsonHelper.ToJson(walletinfo);
                    return;
                }
                httpMessage.result = "createkey error";
            }
            else if (httpMessage.map["0"] == "newtran")
            {
                string rewards = "./tranactiveData/rewards.csv";
                string[] res = File.ReadAllText(rewards).Replace("\r", "").Split("\n");
                MySqlConnection conn = Mysql.GetMySqlConnection3();
                MySqlTransaction transaction = conn.BeginTransaction();
                int nonceTemp = (int.Parse(Program.nonce));
                try
                {
                    for (int i = 0; i < res.Length - 1; i++)
                    {
                        string[] date = res[i].Split(",");
                        string cmd = "transfer";
                        string type = "transfer";
                        string timestamp = date[1];
                        string nonce = (nonceTemp + i) + "";
                        Console.WriteLine(nonce);
                        string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);
                        string addressOut = date[0];
                        string data = "";
                        string amount = date[2];
                        string depend = "";
                        string remarks = "New_Tran";
                        string str_extend = "";
                        string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
                        string hash = CryptoHelper.Sha256(hashdata);
                        string sign = GetSign(hash).ToLower();
                        string sql_update = $"INSERT INTO `transfer`.`tranlist`(`cmd`, `type`, `timestamp`, `addressIn`, `addressOut`, `nonce`, `amount`, `data`, `depend`, `remarks`, `str_extend`, `hash`, `sign`,`state`) VALUES ('{cmd}', '{type}', '{timestamp}', '{addressIn}', '{addressOut}', '{nonce}', '{amount}', '{data}', '{depend}', '{remarks}', '{str_extend}', '{hash}', '{sign}','0');";
                        using (MySqlCommand command = new MySqlCommand(sql_update, conn))
                        {
                            int result = command.ExecuteNonQuery();
                            // result = 1 则 返回真
                            if (result == 0)
                            {
                                throw new Exception("Insert Error");
                            }
                        }

                    }
                    Console.WriteLine("完成数据导入");
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine("数据可能已经导入过了");
                    Console.WriteLine(e);
                    transaction.Rollback();
                    //return;
                }
                finally
                {
                    conn.Dispose();
                }
                while (true)
                {
                    string BestNodeUrl = Program.ruleIP;
                    try
                    {
                        BestNodeUrl = httpMethod("http://101.36.122.116:8000/getminingip", 1000).Replace("\"", "");
                    }
                    catch (Exception e)
                    {
                        BestNodeUrl = Program.ruleIP;
                    }
                    Console.WriteLine(BestNodeUrl);
                    MySqlConnection conn2 = Mysql.GetMySqlConnection3();
                    List<Dictionary<string, string>> tranList = new List<Dictionary<string, string>>();
                    try
                    {
                        string sql = "";
                        sql = "select cmd,type,timestamp,nonce,addressIn,addressOut,data,amount,depend,remarks,str_extend,hash,sign from tranlist where state='0' order by nonce+0 limit 200;";
                        using (MySqlDataReader dt = Mysql.Select(sql, conn2))
                        {
                            if (dt == null)
                            {
                                Console.WriteLine("select dt Error");
                                return;
                            }
                            while (dt.Read())
                            {
                                string cmd = dt["cmd"].ToString();
                                string type = dt["type"].ToString();
                                string timestamp = dt["timestamp"].ToString();
                                string nonce = dt["nonce"].ToString();
                                string addressIn = dt["addressIn"].ToString();
                                string addressOut = dt["addressOut"].ToString();
                                string data = dt["data"].ToString();
                                string amount = dt["amount"].ToString();
                                string depend = dt["depend"].ToString();
                                string remarks = dt["remarks"].ToString();
                                string str_extend = dt["str_extend"].ToString();
                                string hash = dt["hash"].ToString();
                                string sign = dt["sign"].ToString();
                                Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                                transferInfo.Add("cmd", cmd);
                                transferInfo.Add("type", type);
                                transferInfo.Add("timestamp", timestamp);
                                transferInfo.Add("nonce", nonce);
                                transferInfo.Add("addressIn", addressIn);
                                transferInfo.Add("addressOut", addressOut);
                                transferInfo.Add("data", data);
                                transferInfo.Add("amount", amount);
                                transferInfo.Add("depend", depend);
                                transferInfo.Add("remarks", remarks);
                                transferInfo.Add("str_extend", str_extend);
                                transferInfo.Add("hash", hash);
                                transferInfo.Add("sign", sign);
                                tranList.Add(transferInfo);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("select Error");
                        Console.WriteLine(e);
                        return;
                    }
                    finally
                    {
                        conn2.Dispose();
                    }
                    if (tranList.Count == 0)
                    {
                        Console.WriteLine("数据库中已没有未完成的转账");
                        return;
                    }

                    for (int i = 0; i < tranList.Count; i++)
                    {
                        Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                        transferInfo = tranList[i];
                        httpMessage.map.Clear();
                        httpMessage.map.Add("cmd", transferInfo["cmd"]);
                        httpMessage.map.Add("type", transferInfo["type"]);
                        httpMessage.map.Add("hash", transferInfo["hash"]);
                        httpMessage.map.Add("nonce", transferInfo["nonce"]);
                        httpMessage.map.Add("addressIn", transferInfo["addressIn"]);
                        httpMessage.map.Add("addressOut", transferInfo["addressOut"]);
                        httpMessage.map.Add("amount", transferInfo["amount"]);
                        httpMessage.map.Add("data", transferInfo["data"]);
                        httpMessage.map.Add("depend", transferInfo["depend"]);
                        httpMessage.map.Add("sign", transferInfo["sign"]);
                        httpMessage.map.Add("timestamp", transferInfo["timestamp"]);
                        httpMessage.map.Add("remarks", transferInfo["remarks"]);
                        HttpMessage result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        while (result.result == "INVALID URL, set the correct url")
                        {
                            try
                            {
                                BestNodeUrl = httpMethod("http://101.36.122.116:8000/getminingip", 1000).Replace("\"", "");
                            }
                            catch (Exception e)
                            {
                                BestNodeUrl = Program.ruleIP;
                            }
                            Console.WriteLine(BestNodeUrl);
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        }
                        if (result.result.Contains("true"))
                        {
                            Console.WriteLine(transferInfo["nonce"] + ":true");
                        }
                        else
                        {
                            Console.WriteLine(transferInfo["nonce"] + ":false  ----------------"+ result.result);
                        }
                    }
                    Console.WriteLine($"完成nonce:{tranList[0]["nonce"]}-{tranList[tranList.Count - 1]["nonce"]}转账。{DateTime.Now:yyyyMMdd HH: mm:ss}，等待90s进行检查。");
                    Thread.Sleep(90 * 1000);
                    int tranFalseCount = 0;
                    int tranLoseCount = 0;
                    int netErrorCount = 0;
                    int tranSuccess = 0;
                    for (int i = 0; i < tranList.Count; i++)
                    {
                        Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                        transferInfo = tranList[i];
                        httpMessage.map.Clear();
                        httpMessage.map.Add("cmd", "block-by-tranhash");
                        httpMessage.map.Add("hash", transferInfo["hash"]);
                        HttpMessage result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        if (result.result == "INVALID URL, set the correct url")
                        {
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                            if (result.result == "INVALID URL, set the correct url")
                            {
                                netErrorCount += 1;
                                Console.WriteLine("网络或者ip问题");
                                continue;
                            }
                        }
                        if (result.result == "false")
                        {
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                            if (result.result == "false")
                            {
                                tranLoseCount += 1;
                                continue;
                            }

                        }
                        try
                        {
                            var resuleJSON = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                            if (long.Parse(resuleJSON["height"].ToString()) > 0)
                            {
                                tranSuccess += 1;
                                string sql_update = $"update tranlist set state={1} where hash='{transferInfo["hash"]}';";
                                Mysql.ExecuteSql(sql_update);
                                continue;
                            }
                            else if (long.Parse(resuleJSON["height"].ToString()) == 0)  
                            {
                                //这边发现该hash已经是失败的交易，我这边将数据更新一下，改变hash
                                string timestamp = (TimeHelper.Now()).ToString();
                                string hashdata = $"{transferInfo["type"]}#{transferInfo["nonce"]}#{transferInfo["addressIn"]}#{transferInfo["addressOut"]}#{transferInfo["amount"]}#{transferInfo["data"]}#{transferInfo["depend"]}#{timestamp}#{transferInfo["remarks"]}{transferInfo["str_extend"]}";//新版本
                                string hash = CryptoHelper.Sha256(hashdata);
                                string sign = GetSign(hash).ToLower();


                                tranFalseCount += 1;
                                string sql_update = $"update tranlist set timestamp='{timestamp}',hash='{hash}',sign='{sign}' where nonce='{transferInfo["nonce"]}' and addressIn='{transferInfo["addressIn"]}';";
                                Mysql.ExecuteSql(sql_update);
                                continue;
                            }
                            else
                            {
                                tranFalseCount += 1;
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("解析错误：" + e);
                        }
                    }
                    Console.WriteLine($"完成nonce:{tranList[0]["nonce"]}-{tranList[tranList.Count - 1]["nonce"]}检查。{DateTime.Now:yyyy-MM-dd HH: mm:ss}，完成:{tranSuccess} 失败：{tranFalseCount} 查询错误：{netErrorCount} 丢失：{tranLoseCount} ");
                }
                
            }
            else if (httpMessage.map["0"] == "newtran_SAX")
            {
                string rewards = "./tranactiveData/token/rewards.csv";
                string[] res = File.ReadAllText(rewards).Replace("\r", "").Split("\n");
                MySqlConnection conn = Mysql.GetMySqlConnection3();
                MySqlTransaction transaction = conn.BeginTransaction();
                int nonceTemp = (int.Parse(Program.nonce));
                try
                {
                    for (int i = 0; i < res.Length - 1; i++)
                    {
                        string[] date = res[i].Split(",");
                        string cmd = "transfer";
                        string type = "contract";
                        string timestamp = date[1];
                        string nonce = (nonceTemp + i) + "";
                        Console.WriteLine(nonce);
                        string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);
                        string addressOut = "SY64hLHi6sRwzfTosbpyA4nC6gUXyRSCi";
                        string data = $"transfer(\"{date[0]}\",\"{date[2]}\")";
                        string amount = "";
                        string depend = "";
                        string remarks = "New_Tran_Token";
                        string str_extend = "";
                        string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
                        string hash = CryptoHelper.Sha256(hashdata);
                        string sign = GetSign(hash).ToLower();
                        string sql_update = $"INSERT INTO `transfer`.`tranlist`(`cmd`, `type`, `timestamp`, `addressIn`, `addressOut`, `nonce`, `amount`, `data`, `depend`, `remarks`, `str_extend`, `hash`, `sign`,`state`) VALUES ('{cmd}', '{type}', '{timestamp}', '{addressIn}', '{addressOut}', '{nonce}', '{amount}', '{data}', '{depend}', '{remarks}', '{str_extend}', '{hash}', '{sign}','0');";
                        using (MySqlCommand command = new MySqlCommand(sql_update, conn))
                        {
                            int result = command.ExecuteNonQuery();
                            // result = 1 则 返回真
                            if (result == 0)
                            {
                                throw new Exception("Insert Error");
                            }
                        }

                    }
                    Console.WriteLine("完成数据导入");
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine("数据可能已经导入过了");
                    Console.WriteLine(e);
                    transaction.Rollback();
                    //return;
                }
                finally
                {
                    conn.Dispose();
                }
                while (true)
                {
                    string BestNodeUrl = Program.ruleIP;
                    try
                    {
                        BestNodeUrl = httpMethod("http://101.36.122.116:8000/getminingip", 1000).Replace("\"", "");
                    }
                    catch (Exception e)
                    {
                        BestNodeUrl = Program.ruleIP;
                    }
                    Console.WriteLine(BestNodeUrl);
                    MySqlConnection conn2 = Mysql.GetMySqlConnection3();
                    List<Dictionary<string, string>> tranList = new List<Dictionary<string, string>>();
                    try
                    {
                        string sql = "";
                        sql = "select cmd,type,timestamp,nonce,addressIn,addressOut,data,amount,depend,remarks,str_extend,hash,sign from tranlist where state='0' order by nonce+0 limit 200;";
                        using (MySqlDataReader dt = Mysql.Select(sql, conn2))
                        {
                            if (dt == null)
                            {
                                Console.WriteLine("select dt Error");
                                return;
                            }
                            while (dt.Read())
                            {
                                string cmd = dt["cmd"].ToString();
                                string type = dt["type"].ToString();
                                string timestamp = dt["timestamp"].ToString();
                                string nonce = dt["nonce"].ToString();
                                string addressIn = dt["addressIn"].ToString();
                                string addressOut = dt["addressOut"].ToString();
                                string data = dt["data"].ToString();
                                string amount = dt["amount"].ToString();
                                string depend = dt["depend"].ToString();
                                string remarks = dt["remarks"].ToString();
                                string str_extend = dt["str_extend"].ToString();
                                string hash = dt["hash"].ToString();
                                string sign = dt["sign"].ToString();
                                Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                                transferInfo.Add("cmd", cmd);
                                transferInfo.Add("type", type);
                                transferInfo.Add("timestamp", timestamp);
                                transferInfo.Add("nonce", nonce);
                                transferInfo.Add("addressIn", addressIn);
                                transferInfo.Add("addressOut", addressOut);
                                transferInfo.Add("data", data);
                                transferInfo.Add("amount", amount);
                                transferInfo.Add("depend", depend);
                                transferInfo.Add("remarks", remarks);
                                transferInfo.Add("str_extend", str_extend);
                                transferInfo.Add("hash", hash);
                                transferInfo.Add("sign", sign);
                                tranList.Add(transferInfo);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("select Error");
                        Console.WriteLine(e);
                        return;
                    }
                    finally
                    {
                        conn2.Dispose();
                    }
                    if (tranList.Count == 0)
                    {
                        Console.WriteLine("数据库中已没有未完成的转账");
                        return;
                    }

                    for (int i = 0; i < tranList.Count; i++)
                    {
                        Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                        transferInfo = tranList[i];
                        httpMessage.map.Clear();
                        httpMessage.map.Add("cmd", transferInfo["cmd"]);
                        httpMessage.map.Add("type", transferInfo["type"]);
                        httpMessage.map.Add("hash", transferInfo["hash"]);
                        httpMessage.map.Add("nonce", transferInfo["nonce"]);
                        httpMessage.map.Add("addressIn", transferInfo["addressIn"]);
                        httpMessage.map.Add("addressOut", transferInfo["addressOut"]);
                        httpMessage.map.Add("amount", transferInfo["amount"]);
                        httpMessage.map.Add("data", transferInfo["data"]);
                        httpMessage.map.Add("depend", transferInfo["depend"]);
                        httpMessage.map.Add("sign", transferInfo["sign"]);
                        httpMessage.map.Add("timestamp", transferInfo["timestamp"]);
                        httpMessage.map.Add("remarks", transferInfo["remarks"]);
                        HttpMessage result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        while (result.result == "INVALID URL, set the correct url")
                        {
                            try
                            {
                                BestNodeUrl = httpMethod("http://101.36.122.116:8000/getminingip", 1000).Replace("\"", "");
                            }
                            catch (Exception e)
                            {
                                BestNodeUrl = Program.ruleIP;
                            }
                            Console.WriteLine(BestNodeUrl);
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        }
                        if (result.result.Contains("true"))
                        {
                            Console.WriteLine(transferInfo["nonce"] + ":true");
                        }
                        else
                        {
                            Console.WriteLine(transferInfo["nonce"] + ":false  ----------------" + result.result);
                        }
                    }
                    Console.WriteLine($"完成nonce:{tranList[0]["nonce"]}-{tranList[tranList.Count - 1]["nonce"]}转账。{DateTime.Now:yyyyMMdd HH: mm:ss}，等待90s进行检查。");
                    Thread.Sleep(90 * 1000);
                    int tranFalseCount = 0;
                    int tranLoseCount = 0;
                    int netErrorCount = 0;
                    int tranSuccess = 0;
                    for (int i = 0; i < tranList.Count; i++)
                    {
                        Dictionary<string, string> transferInfo = new Dictionary<string, string>();
                        transferInfo = tranList[i];
                        httpMessage.map.Clear();
                        httpMessage.map.Add("cmd", "block-by-tranhash");
                        httpMessage.map.Add("hash", transferInfo["hash"]);
                        HttpMessage result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                        if (result.result == "INVALID URL, set the correct url")
                        {
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                            if (result.result == "INVALID URL, set the correct url")
                            {
                                netErrorCount += 1;
                                Console.WriteLine("网络或者ip问题");
                                continue;
                            }
                        }
                        if (result.result == "false")
                        {
                            result = await ComponentNetworkHttp.QueryCommand(BestNodeUrl + $"/{httpMessage.map["cmd"]}", httpMessage);
                            if (result.result == "false")
                            {
                                tranLoseCount += 1;
                                continue;
                            }

                        }
                        try
                        {
                            var resuleJSON = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                            if (long.Parse(resuleJSON["height"].ToString()) > 0)
                            {
                                tranSuccess += 1;
                                string sql_update = $"update tranlist set state={1} where hash='{transferInfo["hash"]}';";
                                Mysql.ExecuteSql(sql_update);
                                continue;
                            }
                            else if (long.Parse(resuleJSON["height"].ToString()) == 0)
                            {
                                //这边发现该hash已经是失败的交易，我这边将数据更新一下，改变hash,只修改时间戳，不修改其他任何数据
                                string timestamp = (TimeHelper.Now()).ToString();
                                string hashdata = $"{transferInfo["type"]}#{transferInfo["nonce"]}#{transferInfo["addressIn"]}#{transferInfo["addressOut"]}#{transferInfo["amount"]}#{transferInfo["data"]}#{transferInfo["depend"]}#{timestamp}#{transferInfo["remarks"]}{transferInfo["str_extend"]}";//新版本
                                string hash = CryptoHelper.Sha256(hashdata);
                                string sign = GetSign(hash).ToLower();


                                tranFalseCount += 1;
                                string sql_update = $"update tranlist set timestamp='{timestamp}',hash='{hash}',sign='{sign}' where nonce='{transferInfo["nonce"]}' and addressIn='{transferInfo["addressIn"]}';";
                                Mysql.ExecuteSql(sql_update);
                                continue;
                            }
                            else
                            {
                                tranFalseCount += 1;
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("解析错误：" + e);
                        }
                    }
                    Console.WriteLine($"完成nonce:{tranList[0]["nonce"]}-{tranList[tranList.Count - 1]["nonce"]}检查。{DateTime.Now:yyyy-MM-dd HH: mm:ss}，完成:{tranSuccess} 失败：{tranFalseCount} 查询错误：{netErrorCount} 丢失：{tranLoseCount} ");
                }

            }
            else if (httpMessage.map["0"] == "tranactive")
            {
                string progress = "./tranactiveData/progress.json";
                string result = "./tranactiveData/result.json";
                string rewards = "./tranactiveData/rewards.csv";
                string tranfalsefile = "./tranactiveData/tranfalse.json";
                string errfile = "./tranactiveData/errList.json";
                string undeterminedfile = "./tranactiveData/undetermined.json";
                await TranFromCsv1Async(httpMessage, progress, result, rewards, tranfalsefile, errfile, undeterminedfile, 0, 200);
                //await TranFromCsvAsync(httpMessage, progress, result, rewards, 0);//珊瑚网可直接使用
            }
            else if (httpMessage.map["0"] == "tranactive_token")
            {
                string tokenAddress = httpMessage.map["1"];
                string progress = "./tranactiveData/token/progress.json";
                string result = "./tranactiveData/token/result.json";
                string rewards = "./tranactiveData/token/rewards.csv";
                string tranfalsefile = "./tranactiveData/token/tranfalse.json";
                string errfile = "./tranactiveData/token/errList.json";
                string undeterminedfile = "./tranactiveData/token/undetermined.json";
                await TranFromCsv1_tokenAsync(httpMessage, progress, result, rewards, tranfalsefile, errfile, undeterminedfile, 0, 210, tokenAddress);
                //await TranFromCsvAsync(httpMessage, progress, result, rewards, 0);//珊瑚网可直接使用
            }
            else if (httpMessage.map["0"] == "tranold")
            {
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                string csvName = "./AdressReg.csv";
                StreamReader sr = File.OpenText(csvName);
                string jsonWord = sr.ReadToEnd();
                sr.Close();
                string[] arr1 = jsonWord.Split("\n");
                Dictionary<string, float> oData = new Dictionary<string, float>();
                string res = "";
                for (long i = 0; i < arr1.Length - 1; i++)
                {
                    string[] first = arr1[i].Split(";");
                    float oM;
                    if (!oData.ContainsKey(first[1]))
                    {
                        oM = getOldSat(first[0]);
                        oData.Add(first[1], oM);
                        res += first[1].Replace("\r", "") + "," + oM + "\n";
                    }
                }
                string path = "./newData.csv";//文件存放路径，保证文件存在。
                StreamWriter sw = new StreamWriter(path, false);
                sw.WriteLine(res);
                sw.Close();

                string progress = "./progress1.json";
                string result = "./result1.json";
                string rewards = "./newData.csv";
                await TranFromCsvAsync(httpMessage, progress, result, rewards, 1);

            }//弃用
            else if (httpMessage.map["0"] == "getinviter")
            {
                Dictionary<string, string> prog = new Dictionary<string, string>();
                string finName = "./t_invitation.csv";
                StreamReader sr = File.OpenText(finName);
                string jsonWord = sr.ReadToEnd();
                string[] arr = jsonWord.Replace("\r", "").Split("\n");
                sr.Close();

                for (long i = 0; i < arr.Length - 1; i++)
                {
                    string[] ar = arr[i].Replace("\"", "").Split(",");
                    if (ar[0] == "undefined" || ar[0] == "")
                    {
                        continue;
                    }
                    if (prog.ContainsKey(ar[1]))
                    {
                        Console.WriteLine(ar[1] + "  注册的钱包重复了");

                        continue;
                    }
                    prog.Add(ar[1], ar[0]);
                }

                Dictionary<string, string> prog1 = new Dictionary<string, string>();
                finName = "./注册奖励.csv";
                sr = File.OpenText(finName);
                jsonWord = sr.ReadToEnd();
                string[] arr1 = jsonWord.Replace("\r", "").Split("\n");
                sr.Close();
                File.Delete("./邀请人奖励.csv");
                Dictionary<string, string> res = new Dictionary<string, string>();
                List<string> test = new List<string>();
                for (long i = 0; i < arr1.Length - 1; i++)
                {
                    string[] ar = arr1[i].Split(",");

                    if (prog.ContainsKey(ar[0]))
                    {
                        try
                        {
                            res.Add(ar[0], prog[ar[0]]);
                            File.AppendAllText("./邀请人奖励.csv", prog[ar[0]] + ",50" + "\n");
                        }
                        catch
                        {
                            Console.WriteLine(ar[0] + "  注册人重复了");
                        }
                    }
                }
                //for (long i = 0; i < arr1.Length - 1; i++)
                //{
                //    string[] ar = arr1[i].Split(",");

                //    if (prog.ContainsKey(ar[0]))
                //    {
                //        res.Add(ar[0], prog[ar[0]]);
                //        File.AppendAllText("./邀请人奖励.csv", prog[ar[0]] + ",50" + "\n");
                //    }
                //    else
                //    {
                //        File.AppendAllText("./邀请人奖励.csv", "undefined" + ",50" + "\n");
                //    }
                //}
                Console.WriteLine("获取完成");
                //File.WriteAllText("./rewardsNew1.txt",JsonHelper.ToJson(res));
            }
            else if (httpMessage.map["0"] == "gettransfer")
            {
                string address = httpMessage.map["1"];
                long index = 0;
                int numIn = 0;
                int numOut = 0;
                Dictionary<string, string> resIn = new Dictionary<string, string>();
                Dictionary<string, string> resOut = new Dictionary<string, string>();

                while (httpMessage.result != "[]")
                {
                    List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                    httpMessage.map.Clear();
                    httpMessage.map.Add("cmd", "transactions");
                    httpMessage.map.Add("address", address);
                    httpMessage.map.Add("index", index.ToString());
                    httpMessage = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                    index++;
                    list = JsonHelper.FromJson<List<Dictionary<string, string>>>(httpMessage.result);
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i]["addressIn"] != address)
                        {
                            resIn.Add((++numIn).ToString(), list[i]["addressIn"] + "," + list[i]["amount"]);
                        }
                        else if (list[i]["addressOut"] != address)
                        {
                            resOut.Add((++numOut).ToString(), list[i]["addressOut"] + "," + list[i]["amount"]);
                        }
                    }
                }
                Console.WriteLine("转入到该账户：");
                foreach (KeyValuePair<string, string> kv in resIn)
                {
                    Console.WriteLine(kv.Key + kv.Value);
                }
                Console.WriteLine("从该账户转出：");
                foreach (KeyValuePair<string, string> kv in resOut)
                {
                    Console.WriteLine(kv.Key + kv.Value);
                }

            }
            else if (httpMessage.map["0"] == "checktoken")
            {
                await OnCheckTokenAsync(httpMessage);
            }
            else if (httpMessage.map["0"] == "createwallet")
            {
                OnCreat(httpMessage);

            }
            else if (httpMessage.map["0"] == "mempool")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "getlastblock")
            {
                try
                {
                    if (!GetParam(httpMessage, "1", "index", out string index))
                    {
                        httpMessage.result = "command error! \nexample: getlastblock index";
                        return;
                    }
                    string height = await GetHeightAsync();
                    httpMessage.map["1"] = (long.Parse(height) - 19 * long.Parse(httpMessage.map["1"])) != 0 ? (long.Parse(height) - 19 * long.Parse(httpMessage.map["1"])).ToString() : "0";
                    HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                    httpMessage.result = result.result;
                }
                catch (Exception e)
                {
                    httpMessage.result = "command error! \nexample: getlastblock index";
                }
            }
            else if (httpMessage.map["0"] == "transfercount")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "search")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "miner")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "node")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "beruler")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "rules")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "stats")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "account")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "help")
            {
                OnHelp(httpMessage);
            }
            else if (httpMessage.map["0"] == "orderaddress")
            {
                if (!GetParam(httpMessage, "1", "1", out string name))
                {
                    httpMessage.result = "command error! \nexample: orderaddress addressHead";
                    return;
                }
                Console.WriteLine("正在努力的生成您想要的地址~~~addressHead:" + name + "    " + DateTime.Now.ToString("hh:mm:ss"));

                //创建后台工作线程
                ThreadData[] ThreadDataList;
                ThreadDataList = new ThreadData[5];
                List<System.Threading.Thread> threads = new List<Thread>();
                for (int ii = 0; ii < ThreadDataList.Length; ii++)
                {
                    ThreadDataList[ii] = new ThreadData();
                    ThreadDataList[ii].addressHead = name;
                    ThreadDataList[ii].threadNum = (ii + 1).ToString();
                    System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(CustomAddressTool));
                    thread.IsBackground = true;//设置为后台线程
                    thread.Priority = System.Threading.ThreadPriority.Normal;
                    thread.Start(ThreadDataList[ii]);
                    threads.Add(thread);
                }
            }
            else if (httpMessage.map["0"] == "ERCBalance")
            {
                string file = File.ReadAllText("./20210630映射.csv");
                string[] arr = file.Replace("\r", "").Split("\n");
                Core.Core.Block.httpspro pro = new Core.Core.Block.httpspro();
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    var arr2 = arr[i].Split(",");
                    var address = arr2[1];
                    string res = pro.LoginTest("https://eth2.trezor.io/api/v2/address/" + address + "?page=1&pageSize=1&contract=0x1f0f468ee03a6d99cd8a09dd071494a83dc1c0e5");
                    var resBalance = JsonHelper.FromJson<Dictionary<string, object>>(res)["tokens"].ToString();
                    var result = JsonHelper.FromJson<List<Dictionary<string, string>>>(resBalance);
                    var balance = result[0]["balance"];
                    File.AppendAllText("./20210630映射check.csv", arr[i] + "," + balance + "\n");
                }
                Console.WriteLine("获取完成");


            }
            else if (httpMessage.map["0"] == "testIPs")
            {
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                var time = 60 * 4;
                httpMessage.map.Clear();
                httpMessage.map.Add("cmd", "node");
                httpMessage.map.Add("get", "all");
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);


                httpMessage.map.Clear();
                httpMessage.map.Add("cmd", "rules");
                httpMessage.map.Add("get", "all");
                HttpMessage result1 = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                var nodeInfo = result.result;
                var nodeInfoList = JsonHelper.FromJson<List<object>>(nodeInfo);
                var count = 0;

                ThreadData2[] ThreadDataList;
                ThreadDataList = new ThreadData2[nodeInfoList.Count];
                List<System.Threading.Thread> threads = new List<Thread>();
                for (int i = 0; i < ThreadDataList.Length; i++)
                //for (int i = 0; i < 1; i++) 
                {
                    var Node = JsonHelper.FromJson<Dictionary<string, string>>(nodeInfoList[i].ToString());
                    var ip = Node["ipEndPoint"].Replace(":58601", "").Replace(":58602", "");
                    if (result1.result.IndexOf(Node["address"]) != -1)
                    {
                        count = count + 1;
                        Console.WriteLine("ip" + count + "=" + ip + "     " + Node["address"] + "        " + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                        ip = "http://" + ip + ":5000";
                        //ip = "https://wallet.smartx.one/satrpc";
                        ThreadDataList[i] = new ThreadData2();
                        ThreadDataList[i].ip = ip;
                        ThreadDataList[i].time = time;
                        ThreadDataList[i].threadNum = (count).ToString();
                        System.Threading.Thread thread = new System.Threading.Thread(new ParameterizedThreadStart(TestIPsAsync));
                        thread.IsBackground = true;//设置为后台线程
                        thread.Priority = System.Threading.ThreadPriority.Normal;
                        thread.Start(ThreadDataList[i]);
                        threads.Add(thread);

                        //(ip, time, httpMessage);
                    }


                }

            }
            else if (httpMessage.map["0"] == "testIPs2")
            {
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                var time = 2;
                httpMessage.map.Clear();
                httpMessage.map.Add("cmd", "node");
                httpMessage.map.Add("get", "all");
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);


                httpMessage.map.Clear();
                httpMessage.map.Add("cmd", "rules");
                httpMessage.map.Add("get", "all");
                HttpMessage result1 = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                var nodeInfo = result.result;
                var nodeInfoList = JsonHelper.FromJson<List<object>>(nodeInfo);
                var count = 0;

                ThreadData2[] ThreadDataList;
                ThreadDataList = new ThreadData2[nodeInfoList.Count];
                List<System.Threading.Thread> threads = new List<Thread>();
                for (int i = 0; i < 1; i++)
                {

                    count = count + 1;
                    Console.WriteLine("开始测试" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                    var ip = "https://explore.smartx.one/satrpc";
                    ThreadDataList[i] = new ThreadData2();
                    ThreadDataList[i].ip = ip;
                    ThreadDataList[i].time = time;
                    ThreadDataList[i].threadNum = (count).ToString();
                    System.Threading.Thread thread = new System.Threading.Thread(new ParameterizedThreadStart(TestIPsAsync2));
                    thread.IsBackground = true;//设置为后台线程
                    thread.Priority = System.Threading.ThreadPriority.Normal;
                    thread.Start(ThreadDataList[i]);
                    threads.Add(thread);

                    //(ip, time, httpMessage);



                }
            }
            //测试一下代码用例
            else if (httpMessage.map["0"] == "testMyself")
            {
                var res = httpMethod("http://103.100.143.65:5000/?cmd=getrecentblocknode");
                var res1 = JsonHelper.FromJson<List<Dictionary<string, object>>>(res);
                var res2 = res1[1]["Value"].ToString();
                var res3 = JArray.Parse(res2);
                var res4 = res3[1].ToString();
                Console.WriteLine(res4);
                Console.WriteLine(res4.GetType());
            }
            else
            {
                httpMessage.result = "command error";
            }
        }
        private static string httpMethod(string p_url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(p_url);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }

        private static async void TestIPsAsync( object data) 
        {
            ThreadData2 This = data as ThreadData2;
            string ip = This.ip;
            int time = This.time;
            string threadNum = This.threadNum;
            HttpMessage httpMessage = new HttpMessage();
            httpMessage.map = new Dictionary<string, string>();
            Console.WriteLine(threadNum + "开始转账" + time + "高度，请等待" + time / 4 + "分钟");
            while (time > 0)
            {
                httpMessage.map.Clear();
                httpMessage.map.Add("0", "transfer");
                httpMessage.map.Add("1", "dzY6xwsjF8WKS9xQn7x5D8SLL53PDbeX4");
                httpMessage.map.Add("2", "0.00001");
                httpMessage.map.Add("3", "0");
                httpMessage.map.Add("cmd", "transfer");
                await OnTransferTestIPsAsync(ip, httpMessage);
                time--;
                Thread.Sleep(15 * 1000);
                
            }
            Console.WriteLine(threadNum + "已经完成转账,等待75s开始检查");
            Thread.Sleep(75 * 1000);
            Console.WriteLine(threadNum + "开始检查");
            string csvName = "./TestIPs" + ip.Replace("https://", "").Replace("http://", "").Replace(":5000", "").Replace(".", "") + ".csv";
            //string csvName = "./TestIPs" + "wallet" + ".csv";
            StreamReader sr1 = File.OpenText(csvName);
            string jsonWord1 = sr1.ReadToEnd();
            string[] arr = jsonWord1.Split("\n");
            sr1.Close();
            var falseCount = 0;
            var noReasonCount = 0;
            var interfaceErrorCount = 0;
            for (int i = 0; i < arr.Length - 1; i++) 
            {
                var arr2 = arr[i].Split(",");
                httpMessage.map.Clear();
                httpMessage.map.Add("hash", arr2[2]);                
                httpMessage.map.Add("cmd", "block-by-tranhash");
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                //Console.WriteLine("验证信息结果"+result.result);//明天这边看一下结果然后看一下
                if (result.result == "INVALID URL, set the correct url")
                {
                    File.AppendAllText(csvName, arr[i]+ ","+"INVALID URL, set the correct url" + "\n");
                    interfaceErrorCount += 1;
                }
                else if (result.result == "false")
                {
                    File.AppendAllText(csvName, arr[i] + "," + "FALSE" + "\n");
                    falseCount += 1;
                }
                else if (result.result.IndexOf("height")!=-1)
                {
                    File.AppendAllText(csvName, arr[i] + "," + "TRUE" + "\n");
                }
                else 
                {
                    Console.WriteLine("不清楚什么原因："+ arr2[2]+"     "+ ip);
                    File.AppendAllText(csvName, arr[i] + "," + "不清楚什么原因" + "\n");
                    noReasonCount += 1;
                }
            }
            Console.WriteLine(threadNum +"      "+ ip + "已经完成检查。  " +"       丢失个数："+falseCount+"        意外错误个数："+ noReasonCount+"       接口访问失败个数："+ interfaceErrorCount);
        }
        private static async void TestIPsAsync2(object data)
        {
            ThreadData2 This = data as ThreadData2;
            string ip = This.ip;
            int time = This.time;
            string threadNum = This.threadNum;
            HttpMessage httpMessage = new HttpMessage();
            httpMessage.map = new Dictionary<string, string>();
            Console.WriteLine(threadNum + "开始转账"+time+"高度，请等待"+time/4+"分钟");
            while (time > 0)
            {
                httpMessage.map.Clear();
                httpMessage.map.Add("0", "transfer");
                httpMessage.map.Add("1", "dzY6xwsjF8WKS9xQn7x5D8SLL53PDbeX4");
                httpMessage.map.Add("2", "0.00001");
                httpMessage.map.Add("3", "0");
                httpMessage.map.Add("cmd", "transfer");
                await OnTransferTestIPsAsync2(ip, httpMessage);
                time--;
                Thread.Sleep(15 * 1000);

            }
            Console.WriteLine(threadNum + "已经完成转账,等待75s开始检查");
            Thread.Sleep(75 * 1000);
            Console.WriteLine(threadNum + "开始检查");
            string csvName = "./TestIPs" + "explore" + ".csv";
            StreamReader sr1 = File.OpenText(csvName);
            string jsonWord1 = sr1.ReadToEnd();
            string[] arr = jsonWord1.Split("\n");
            sr1.Close();
            var falseCount = 0;
            var noReasonCount = 0;
            var interfaceErrorCount = 0;
            for (int i = 0; i < arr.Length - 1; i++)
            {
                var arr2 = arr[i].Split(",");
                httpMessage.map.Clear();
                httpMessage.map.Add("hash", arr2[2]);
                httpMessage.map.Add("cmd", "block-by-tranhash");
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                //Console.WriteLine("验证信息结果"+result.result);//明天这边看一下结果然后看一下
                if (result.result == "INVALID URL, set the correct url")
                {
                    File.AppendAllText(csvName, arr[i] + "," + "INVALID URL, set the correct url" + "\n");
                    interfaceErrorCount += 1;
                }
                else if (result.result == "false")
                {
                    File.AppendAllText(csvName, arr[i] + "," + "FALSE" + "\n");
                    falseCount += 1;
                }
                else if (result.result.IndexOf("height") != -1)
                {
                    File.AppendAllText(csvName, arr[i] + "," + "TRUE" + "\n");
                }
                else
                {
                    Console.WriteLine("不清楚什么原因：" + arr2[2] + "     " + ip);
                    File.AppendAllText(csvName, arr[i] + "," + "不清楚什么原因" + "\n");
                    noReasonCount += 1;
                }
            }
            Console.WriteLine(threadNum + "      " + ip + "已经完成检查。  " + "       丢失个数：" + falseCount + "        意外错误个数：" + noReasonCount + "       接口访问失败个数：" + interfaceErrorCount);
        }

        private static async System.Threading.Tasks.Task TranFromCsvAsync(HttpMessage httpMessage, string progress, string result1, string rewards,long type)
        {
            //判断有没有设置默认钱包
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                return;
            }
            ////如果程序中断则读取中断之前的文件，判断从什么地方开始
            //List<Dictionary<string, string>> tranSuccessList = new List<Dictionary<string, string>>();
            //Dictionary<string, string> tranSuccess = new Dictionary<string, string>();
            //string fileName = result1;
            //StreamReader reader = File.OpenText(fileName);
            //string fileContent = reader.ReadToEnd();
            //tranSuccessList = JsonHelper.FromJson<List<Dictionary<string, string>>>(fileContent);




            //读取progress.json文件 查看是否完成 与 转账错误失败的个数
            Dictionary<string, string> prog = new Dictionary<string, string>();
            string finName = progress;
            StreamReader sr = File.OpenText(finName);
            string jsonWord = sr.ReadToEnd();
            prog = JsonHelper.FromJson<Dictionary<string, string>>(jsonWord);
            sr.Close();
            //转账错误的个数
            string errNum = prog["errNum"];
            //判断是否完成转账
            if (prog["accomlish"] != "0")//
            {
                //警告已完成
                Console.WriteLine("转账已经完成，要重新转账吗？ (Y/N)");
                string goON = Console.ReadLine();
                if (goON == "Y" || goON == "y")
                {
                    Dictionary<string, string> prog2 = new Dictionary<string, string>();
                    prog2.Add("accomlish", "0");
                    prog2.Add("errNum", "0");
                    string path2 = progress;//文件存放路径，保证文件存在。
                    StreamWriter sw2 = new StreamWriter(path2, false);
                    sw2.WriteLine(JsonHelper.ToJson(prog2));
                    sw2.Close();

                    string path = result1;//文件存放路径，保证文件存在。
                    StreamWriter sw = new StreamWriter(path, false);
                    sw.WriteLine("");
                    sw.Close();
                    httpMessage.result = "数据已经重置，可以重新转账";
                }
                return;
            }

            //读取文件将文件的地址和需要转账的数量读入内存
            string csvName = rewards;
            StreamReader sr1 = File.OpenText(csvName);
            string jsonWord1 = sr1.ReadToEnd();
            string[] arr = jsonWord1.Split("\n");
            sr1.Close();

            long index;//从第多少个数据开始转账，如果转账中断重新转账就需要这个
            Dictionary<string, string> result = new Dictionary<string, string>();
            //List<Dictionary<string, string>> results = new List<Dictionary<string, string>>(); //需要将数据全部打包成json文件时候打开生成就行，配合下面的add
            try
            {
                string csvResName = result1;
                StreamReader srRes = File.OpenText(csvResName);
                string jsonWordRes = srRes.ReadToEnd();
                string[] arrRes = jsonWordRes.Split("\n");
                srRes.Close();
                index = (long)(arrRes.Length - 2 + long.Parse(errNum));
            }
            catch (Exception)
            {
                index = 0;
            }
            if (index >= (arr.Length - type - 1))
            {
                prog.Clear();
                prog.Add("accomlish", "1");
                prog.Add("errNum", errNum);
                string path1 = progress;//文件存放路径，保证文件存在。
                StreamWriter sw1 = new StreamWriter(path1, false);
                sw1.WriteLine(JsonHelper.ToJson(prog));
                sw1.Close();
                httpMessage.result = "转账完成。";
                return;
            }
            //得到csv文件的数据之后进行遍历，转账
            for (long i = index; i < arr.Length - type - 1; i++) 
            {
                string[] csvd = arr[i].Split(",");
                initHttpMessage(httpMessage, csvd); //初始化httpmessage的信息 准备进行转账
                await OnTransferAsync(httpMessage); //进行转账
                if (httpMessage.map.ContainsKey("result")) //转账失败 这样的话httpmessage的信息不会改变就没有map就将失败的地址列出来
                {
                    //可以给个文件然后将错误账号金额写进去未完成
                    if (!GetParam(httpMessage, "1", "addressOut", out string addressOut))
                    {
                        httpMessage.result = "错误，然后地址出问题了";
                        return;
                    }
                    Console.WriteLine(addressOut);
                    errNum = (long.Parse(errNum) + 1).ToString();
                    prog["errNum"] = errNum;
                    File.WriteAllText(progress, JsonHelper.ToJson(prog));
                    continue;
                }
                //转账成功，将数据写入字典tranSuccessList中
                //tranSuccess.Add("address", csvd[0]);
                //tranSuccess.Add("account", float.Parse(csvd[1]).ToString());
                //tranSuccess.Add("hash", httpMessage.map["hash"]);
                //tranSuccessList.Add(tranSuccess);
                //转账成功 将数据写入到result.json文件中
                result.Add("address", csvd[0]);
                result.Add("account", float.Parse(csvd[1]).ToString());
                result.Add("hash", httpMessage.map["hash"]);
                string res = JsonHelper.ToJson(result);
                //results.Add(result);
                string path = result1;//文件存放路径，保证文件存在。
                StreamWriter sw = new StreamWriter(path, true);
                sw.WriteLine(res);
                sw.Close();
                result.Clear();//清楚result 下次重新写入数据
                //到了最后转账和数据写入完成，写入结束标记
                if (i == (arr.Length - type - 2)) 
                {
                    //转账完成将全局字典写进文件未完成
                    prog.Clear();
                    prog.Add("accomlish", "1");
                    prog.Add("errNum", errNum);
                    string path1 = progress;//文件存放路径，保证文件存在。
                    StreamWriter sw1 = new StreamWriter(path1, false);
                    sw1.WriteLine(JsonHelper.ToJson(prog));
                    sw1.Close();
                    httpMessage.result = "转账完成。"+DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
                }
            }
        }

        private static async System.Threading.Tasks.Task TranFromCsv1Async(HttpMessage httpMessage, string progress, string result1, string rewards,string tranfalsefile,string errfile,string undeterminedfile, long type,long num)
        {
            try
            {
                //判断有没有设置默认钱包
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                //如果程序中断则读取中断之前的文件，判断从什么地方开始
                List<Dictionary<string, string>> tranSuccessList = new List<Dictionary<string, string>>();
                string fileName = result1;
                StreamReader reader = File.OpenText(fileName);
                string fileContent = reader.ReadToEnd();
                reader.Close();
                if (fileContent != "" && fileContent != "\r\n")
                {
                    tranSuccessList = JsonHelper.FromJson<List<Dictionary<string, string>>>(fileContent);
                }
                //如果程序中断则读取中断之前的错误文件
                List<Dictionary<string, string>> errList = new List<Dictionary<string, string>>();
                fileContent = File.ReadAllText(errfile);
                if (fileContent != "" && fileContent != "\r\n")
                {
                    errList = JsonHelper.FromJson<List<Dictionary<string, string>>>(fileContent);
                }
                //如果程序中断则读取之前的未确定文件
                List<Dictionary<string, string>> undeterminedList = new List<Dictionary<string, string>>();
                fileContent = File.ReadAllText(undeterminedfile);
                if (fileContent != "[]" && fileContent != "" && fileContent != "\r\n")
                {
                    Console.WriteLine("上次转账有未确定转账，请确认解决问题了（Y/N）");
                    string determined = Console.ReadLine();
                    if (determined == "Y" || determined == "y")
                    {
                        File.WriteAllText(undeterminedfile, "[]");
                        //重写进度文件
                        Dictionary<string, string> prog2 = new Dictionary<string, string>();
                        prog2.Add("accomlish", "0");
                        prog2.Add("errNum", "0");
                        File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                        //清空结果文件
                        File.WriteAllText(result1, "");

                        //清空错误文件
                        File.WriteAllText(errfile, "[]");
                            
                        httpMessage.result = "未确定文件已经重置，可以重新转账";
                        return;
                    }

                }


                try
                {
                    //读取progress.json文件 查看是否完成 与 转账错误失败的个数
                    Dictionary<string, string> prog = new Dictionary<string, string>();
                    string finName = progress;
                    StreamReader sr = File.OpenText(finName);
                    string jsonWord = sr.ReadToEnd();

                    prog = JsonHelper.FromJson<Dictionary<string, string>>(jsonWord);
                    sr.Close();
                    //转账错误的个数
                    string errNum = prog["errNum"];
                    //判断是否完成转账
                    if (prog["accomlish"] != "0")//
                    {
                        //警告已完成
                        Console.WriteLine("转账已经完成，要重新转账吗？ (Y/N)");
                        string goON = Console.ReadLine();
                        if (goON == "Y" || goON == "y")
                        {
                            //重写进度文件
                            Dictionary<string, string> prog2 = new Dictionary<string, string>();
                            prog2.Add("accomlish", "0");
                            prog2.Add("errNum", "0");
                            File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                            //清空结果文件
                            File.WriteAllText(result1, "");

                            //清空错误文件
                            File.WriteAllText(errfile, "[]");

                            //清空未确定文件
                            File.WriteAllText(undeterminedfile, "[]");

                            httpMessage.result = "数据已经重置，可以重新转账";
                        }
                        return;
                    }

                    //读取文件将文件的地址和需要转账的数量读入内存
                    string csvName = rewards;
                    StreamReader sr1 = File.OpenText(csvName);
                    string jsonWord1 = sr1.ReadToEnd();
                    string[] arr = jsonWord1.Split("\n");
                    sr1.Close();

                    long index = 0;//从第多少个数据开始转账，如果转账中断重新转账就需要这个

                    try
                    {
                        //根据转账成功的最后一个数据决定index
                        for (int i = 0; i < arr.Length - type - 1; i++)
                        {
                            string[] csvd = arr[i].Split(",");
                            if (csvd[0] == tranSuccessList[tranSuccessList.Count - 1]["address"])
                            {
                                index = i + 1;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        index = 0;
                    }
                    if (index >= (arr.Length - type - 1))
                    {
                        prog.Clear();
                        prog.Add("accomlish", "1");
                        prog.Add("errNum", errNum);
                        File.WriteAllText(progress, JsonHelper.ToJson(prog));
                        httpMessage.result = "转账完成。";
                        return;
                    }
                    while (index < (arr.Length - type - 1))
                    {

                        long times = (index + num) < (arr.Length - type - 1) ? (index + num) : (arr.Length - type - 1);
                        //得到csv文件的数据之后进行遍历，转账
                        for (long i = index; i < times; i++)
                        {

                            string[] csvd = arr[i].Split(",");
                            ////代币转账
                            //initHttpMessage_token(httpMessage, csvd,""); //初始化httpmessage的信息 准备进行转账     注意这边填写代币地址
                            //await OnTransfer_tokenAsync(httpMessage); //进行转账
                            //SAT转账
                            initHttpMessage(httpMessage, csvd); //初始化httpmessage的信息 准备进行转账
                            await OnTransferAsync(httpMessage); //进行转账
                            //转账失败 这样的话httpmessage的信息包括result，转账失败的原因
                            if (httpMessage.map.ContainsKey("result"))
                            {
                                int temp = 0;
                                string address = "";
                                string amount = "";
                                //可以给个文件然后将错误账号、金额、错误类型写进去未完成
                                if (httpMessage.result == "false")
                                {
                                    address = httpMessage.map["addressOut"];
                                    amount = httpMessage.map["amount"].Replace("0000", "");
                                }
                                else
                                {
                                    address = httpMessage.map["1"];
                                    amount = httpMessage.map["2"];
                                }

                                Console.WriteLine(address);

                                errNum = (long.Parse(errNum) + 1).ToString();
                                prog["errNum"] = errNum;
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));
                                //foreach (var ii in errList)
                                //{
                                //    if (ii["address"] == address && ii["amount"] == (httpMessage.map["2"].Replace("\r", "")))
                                //    {
                                //        temp = 1;
                                //        break;
                                //    }
                                //}
                                if (temp == 0)
                                {
                                    Dictionary<string, string> res = new Dictionary<string, string>();
                                    res.Add("address", address);
                                    res.Add("amount", amount.Replace("\r", ""));
                                    res.Add("errtype", httpMessage.map["result"]);
                                    res.Add("time", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                    errList.Add(res);

                                }
                                if (i == (times - 1))
                                {
                                    //转账完成将全局字典写进文件
                                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));

                                    //转账完成将完成标记写入
                                    prog.Clear();
                                    prog.Add("accomlish", "1");
                                    prog.Add("errNum", errNum);
                                    File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                    //转账完成将错误数据写入
                                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                    httpMessage.result = "转账完成。";

                                    index = times;
                                    Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                }
                                continue;
                            }
                            //转账成功，将数据写入字典tranSuccessList中
                            Dictionary<string, string> tranSuccess = new Dictionary<string, string>();
                            tranSuccess.Add("address", csvd[0]);
                            tranSuccess.Add("amount", float.Parse(csvd[1]).ToString());
                            tranSuccess.Add("hash", httpMessage.map["hash"]);
                            tranSuccess.Add("accindex", httpMessage.map["accindex"]);
                            tranSuccessList.Add(tranSuccess);



                            //到了最后转账和数据写入完成，写入结束标记
                            if (i == (arr.Length - type - 2))
                            {
                                //转账完成将全局字典写进文件
                                string path = result1;//文件存放路径，保证文件存在。
                                StreamWriter sw = new StreamWriter(path, false);
                                sw.WriteLine(JsonHelper.ToJson(tranSuccessList));
                                sw.Close();

                                //转账完成将完成标记写入
                                prog.Clear();
                                prog.Add("accomlish", "1");
                                prog.Add("errNum", errNum);
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                //转账完成将错误数据写入
                                File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                httpMessage.result = "转账完成。";
                            }

                            if (i == (times - 1))
                            {
                                index = times;
                                Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                            }


                        }
                        List<Dictionary<string, string>> tranfalse = new List<Dictionary<string, string>>();
                        int status = 0;//0代表没问题  1代表有数据未查询出来
                        if (tranSuccessList.Count>0)
                        {
                            Thread.Sleep(90 * 1000);//等待3分钟 之后判断后面的转账是否成功
                        }
                        Console.WriteLine("等待完毕，开始验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                        for (int i = 0; i < tranSuccessList.Count; i++)
                        {
                            initCheckHttpMessage(httpMessage, tranSuccessList[i]);
                            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                            //Console.WriteLine("验证信息结果"+result.result);//明天这边看一下结果然后看一下
                            if (result.result == "INVALID URL, set the correct url")
                            {
                                status = 1;
                                Console.WriteLine("网络或者ip问题");
                                break;
                            }
                            if (result.result == "false")
                            {
                                status = 1;
                                tranfalse.Add(tranSuccessList[i]);
                                break;
                            }
                            try
                            {
                                var res = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                                if (long.Parse(res["height"].ToString()) == 0)
                                {
                                    tranfalse.Add(tranSuccessList[i]);
                                }
                            }
                            catch (Exception e) {
                                tranfalse.Add(tranSuccessList[i]);
                                Console.WriteLine("解析错误："+e);
                            }
                        }
                        if (status == 1)
                        {
                            File.WriteAllText(undeterminedfile, JsonHelper.ToJson(tranSuccessList));
                            httpMessage.result = "该次转账未确定" + tranSuccessList.Count + "个";
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }
                        
                        File.WriteAllText(tranfalsefile, JsonHelper.ToJson(tranfalse));
                        Console.WriteLine("该次转账共失败" + tranfalse.Count + "个");
                        tranSuccessList.Clear();
                        tranfalse.Clear();
                        httpMessage.result = "";
                        if (tranfalse.Count > 0)
                        {
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));//写入结果文件
                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));//写入错误文件
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static async System.Threading.Tasks.Task TranFromCsv1_tokenAsync_new(HttpMessage httpMessage, string progress, string result1, string rewards, string tranfalsefile, string errfile, string undeterminedfile, long type, long num, string tokenAddress)
        {
            try
            {
                //判断有没有设置默认钱包
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                //如果程序中断则读取中断之前的文件，判断从什么地方开始
                List<Dictionary<string, string>> tranSuccessList = new List<Dictionary<string, string>>();
                
                List<Dictionary<string, string>> errList = new List<Dictionary<string, string>>();
                
                //如果程序中断则读取之前的未确定文件
                List<Dictionary<string, string>> undeterminedList = new List<Dictionary<string, string>>();
                string fileContent = File.ReadAllText(undeterminedfile);
                if (fileContent != "[]" && fileContent != "" && fileContent != "\r\n")
                {
                    Console.WriteLine("上次转账有未确定转账，请确认解决问题了（Y/N）");
                    string determined = Console.ReadLine();
                    if (determined == "Y" || determined == "y")
                    {
                        File.WriteAllText(undeterminedfile, "[]");
                        //重写进度文件
                        Dictionary<string, string> prog2 = new Dictionary<string, string>();
                        prog2.Add("accomlish", "0");
                        prog2.Add("errNum", "0");
                        File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                        //清空结果文件
                        File.WriteAllText(result1, "");

                        //清空错误文件
                        File.WriteAllText(errfile, "[]");

                        httpMessage.result = "未确定文件已经重置，可以重新转账";
                        return;
                    }

                }


                try
                {
                    //读取progress.json文件 查看是否完成 与 转账错误失败的个数
                    Dictionary<string, string> prog = new Dictionary<string, string>();
                    string finName = progress;
                    StreamReader sr = File.OpenText(finName);
                    string jsonWord = sr.ReadToEnd();

                    prog = JsonHelper.FromJson<Dictionary<string, string>>(jsonWord);
                    sr.Close();
                    //转账错误的个数
                    string errNum = prog["errNum"];
                    //判断是否完成转账
                    if (prog["accomlish"] != "0")//
                    {
                        //警告已完成
                        Console.WriteLine("转账已经完成，要重新转账吗？ (Y/N)");
                        string goON = Console.ReadLine();
                        if (goON == "Y" || goON == "y")
                        {
                            //重写进度文件
                            Dictionary<string, string> prog2 = new Dictionary<string, string>();
                            prog2.Add("accomlish", "0");
                            prog2.Add("errNum", "0");
                            File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                            //清空结果文件
                            File.WriteAllText(result1, "");

                            //清空错误文件
                            File.WriteAllText(errfile, "[]");

                            //清空未确定文件
                            File.WriteAllText(undeterminedfile, "[]");

                            httpMessage.result = "数据已经重置，可以重新转账";
                        }
                        return;
                    }

                    //读取文件将文件的地址和需要转账的数量读入内存
                    string csvName = rewards;
                    StreamReader sr1 = File.OpenText(csvName);
                    string jsonWord1 = sr1.ReadToEnd();
                    string[] arr = jsonWord1.Split("\n");
                    sr1.Close();

                    long index = 0;//从第多少个数据开始转账

                    if (index >= (arr.Length - type - 1))
                    {
                        prog.Clear();
                        prog.Add("accomlish", "1");
                        prog.Add("errNum", errNum);
                        File.WriteAllText(progress, JsonHelper.ToJson(prog));
                        httpMessage.result = "转账完成。";
                        return;
                    }
                    while (index < (arr.Length - type - 1))
                    {

                        long times = (index + num) < (arr.Length - type - 1) ? (index + num) : (arr.Length - type - 1);
                        //得到csv文件的数据之后进行遍历，转账
                        for (long i = index; i < times; i++)
                        {
                            string[] csvd = arr[i].Split(",");
                            //代币转账
                            initHttpMessage_token_new(httpMessage, csvd, tokenAddress); //初始化httpmessage的信息 准备进行转账     注意这边填写代币地址
                            await OnTransfer_tokenAsync_new(httpMessage); //进行转账
                            //SAT转账
                            //initHttpMessage(httpMessage, csvd); //初始化httpmessage的信息 准备进行转账
                            //await OnTransferAsync(httpMessage); //进行转账
                            //转账失败 这样的话httpmessage的信息包括result，转账失败的原因
                            if (httpMessage.map.ContainsKey("result"))
                            {
                                int temp = 0;
                                string address = "";
                                string amount = "";
                                //可以给个文件然后将错误账号、金额、错误类型写进去未完成
                                if (httpMessage.result == "false")
                                {
                                    address = httpMessage.map["data"];
                                    amount = httpMessage.map["amount"].Replace("0000", "");
                                }
                                else
                                {
                                    address = httpMessage.map["1"];
                                    amount = httpMessage.map["2"];
                                }

                                Console.WriteLine(address);

                                errNum = (long.Parse(errNum) + 1).ToString();
                                prog["errNum"] = errNum;
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));
                                //foreach (var ii in errList)
                                //{
                                //    if (ii["address"] == address && ii["amount"] == (httpMessage.map["2"].Replace("\r", "")))
                                //    {
                                //        temp = 1;
                                //        break;
                                //    }
                                //}
                                if (temp == 0)
                                {
                                    Dictionary<string, string> res = new Dictionary<string, string>();
                                    res.Add("address", address);
                                    res.Add("amount", amount.Replace("\r", ""));
                                    res.Add("errtype", httpMessage.map["result"]);
                                    res.Add("time", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                    errList.Add(res);
                                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));
                                }
                                if (i == (times - 1))
                                {
                                    //转账完成将全局字典写进文件
                                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));
                                    //转账完成将完成标记写入
                                    prog.Clear();
                                    prog.Add("accomlish", "1");
                                    prog.Add("errNum", errNum);
                                    File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                    //转账完成将错误数据写入
                                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                    httpMessage.result = "转账完成。";

                                    index = times;
                                    Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                }
                                continue;
                            }
                            //转账成功，将数据写入字典tranSuccessList中
                            Dictionary<string, string> tranSuccess = new Dictionary<string, string>();
                            tranSuccess.Add("address", csvd[0]);
                            tranSuccess.Add("amount", float.Parse(csvd[1]).ToString());
                            tranSuccess.Add("hash", httpMessage.map["hash"]);
                            tranSuccess.Add("accindex", httpMessage.map["accindex"]);
                            tranSuccessList.Add(tranSuccess);



                            //到了最后转账和数据写入完成，写入结束标记
                            if (i == (arr.Length - type - 2))
                            {
                                //转账完成将全局字典写进文件
                                string path = result1;//文件存放路径，保证文件存在。
                                StreamWriter sw = new StreamWriter(path, false);
                                sw.WriteLine(JsonHelper.ToJson(tranSuccessList));
                                sw.Close();

                                //转账完成将完成标记写入
                                prog.Clear();
                                prog.Add("accomlish", "1");
                                prog.Add("errNum", errNum);
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                //转账完成将错误数据写入
                                File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                httpMessage.result = "转账完成。";
                            }

                            if (i == (times - 1))
                            {
                                index = times;
                                Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                            }


                        }
                        List<Dictionary<string, string>> tranfalse = new List<Dictionary<string, string>>();
                        List<Dictionary<string, string>> tranundetermined = new List<Dictionary<string, string>>();
                        int status = 0;//0代表没问题  1代表有数据未查询出来
                        if (tranSuccessList.Count > 0)
                        {
                            Thread.Sleep(90 * 1000);//等待3分钟 之后判断后面的转账是否成功
                        }
                        Console.WriteLine("等待完毕，开始验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                        for (int i = 0; i < tranSuccessList.Count; i++)
                        {
                            initCheckHttpMessage(httpMessage, tranSuccessList[i]);
                            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                            //Console.WriteLine("验证信息结果"+result.result);//明天这边看一下结果然后看一下
                            if (result.result == "INVALID URL, set the correct url")
                            {
                                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                                if (result.result == "INVALID URL, set the correct url")
                                {
                                    status = 3;
                                    Console.WriteLine("网络或者ip问题");
                                    tranundetermined.Add(tranSuccessList[i]);
                                    continue;
                                }
                            }
                            if (result.result == "false")
                            {
                                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                                if (result.result == "false")
                                {
                                    status = 1;
                                    tranfalse.Add(tranSuccessList[i]);
                                    continue;
                                    //break;
                                }

                            }
                            try
                            {
                                var res = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                                if (long.Parse(res["height"].ToString()) == 0)
                                {
                                    tranfalse.Add(tranSuccessList[i]);
                                }
                            }
                            catch (Exception e)
                            {
                                tranfalse.Add(tranSuccessList[i]);
                                Console.WriteLine("解析错误：" + e);
                            }
                        }
                        if (status == 1 || status == 3)
                        {
                            File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));//写入结果文件

                            File.WriteAllText(undeterminedfile, JsonHelper.ToJson(tranundetermined));
                            httpMessage.result = "该次转账未确定" + tranundetermined.Count + "个";
                            File.WriteAllText(tranfalsefile, JsonHelper.ToJson(tranfalse));
                            Console.WriteLine("该次转账共失败" + tranfalse.Count + "个");
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }

                        File.WriteAllText(tranfalsefile, JsonHelper.ToJson(tranfalse));
                        Console.WriteLine("该次转账共失败" + tranfalse.Count + "个");
                        tranSuccessList.Clear();
                        tranfalse.Clear();
                        httpMessage.result = "";
                        if (tranfalse.Count > 0)
                        {
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                    Program.nonce = (int.Parse(nonce) + 1).ToString();
                    Console.WriteLine(e.Message);
                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));//写入结果文件
                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));//写入错误文件
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static async System.Threading.Tasks.Task TranFromCsv1_tokenAsync(HttpMessage httpMessage, string progress, string result1, string rewards, string tranfalsefile, string errfile, string undeterminedfile, long type, long num,string tokenAddress)
        {
            try
            {
                //判断有没有设置默认钱包
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                //如果程序中断则读取中断之前的文件，判断从什么地方开始
                List<Dictionary<string, string>> tranSuccessList = new List<Dictionary<string, string>>();
                string fileName = result1;
                StreamReader reader = File.OpenText(fileName);
                string fileContent = reader.ReadToEnd();
                reader.Close();
                if (fileContent != "" && fileContent != "\r\n")
                {
                    tranSuccessList = JsonHelper.FromJson<List<Dictionary<string, string>>>(fileContent);
                }
                //如果程序中断则读取中断之前的错误文件
                List<Dictionary<string, string>> errList = new List<Dictionary<string, string>>();
                fileContent = File.ReadAllText(errfile);
                if (fileContent != "" && fileContent != "\r\n")
                {
                    errList = JsonHelper.FromJson<List<Dictionary<string, string>>>(fileContent);
                }
                //如果程序中断则读取之前的未确定文件
                List<Dictionary<string, string>> undeterminedList = new List<Dictionary<string, string>>();
                fileContent = File.ReadAllText(undeterminedfile);
                if (fileContent != "[]" && fileContent != "" && fileContent != "\r\n")
                {
                    Console.WriteLine("上次转账有未确定转账，请确认解决问题了（Y/N）");
                    string determined = Console.ReadLine();
                    if (determined == "Y" || determined == "y")
                    {
                        File.WriteAllText(undeterminedfile, "[]");
                        //重写进度文件
                        Dictionary<string, string> prog2 = new Dictionary<string, string>();
                        prog2.Add("accomlish", "0");
                        prog2.Add("errNum", "0");
                        File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                        //清空结果文件
                        File.WriteAllText(result1, "");

                        //清空错误文件
                        File.WriteAllText(errfile, "[]");

                        httpMessage.result = "未确定文件已经重置，可以重新转账";
                        return;
                    }

                }


                try
                {
                    //读取progress.json文件 查看是否完成 与 转账错误失败的个数
                    Dictionary<string, string> prog = new Dictionary<string, string>();
                    string finName = progress;
                    StreamReader sr = File.OpenText(finName);
                    string jsonWord = sr.ReadToEnd();

                    prog = JsonHelper.FromJson<Dictionary<string, string>>(jsonWord);
                    sr.Close();
                    //转账错误的个数
                    string errNum = prog["errNum"];
                    //判断是否完成转账
                    if (prog["accomlish"] != "0")//
                    {
                        //警告已完成
                        Console.WriteLine("转账已经完成，要重新转账吗？ (Y/N)");
                        string goON = Console.ReadLine();
                        if (goON == "Y" || goON == "y")
                        {
                            //重写进度文件
                            Dictionary<string, string> prog2 = new Dictionary<string, string>();
                            prog2.Add("accomlish", "0");
                            prog2.Add("errNum", "0");
                            File.WriteAllText(progress, JsonHelper.ToJson(prog2));

                            //清空结果文件
                            File.WriteAllText(result1, "");

                            //清空错误文件
                            File.WriteAllText(errfile, "[]");

                            //清空未确定文件
                            File.WriteAllText(undeterminedfile, "[]");

                            httpMessage.result = "数据已经重置，可以重新转账";
                        }
                        return;
                    }

                    //读取文件将文件的地址和需要转账的数量读入内存
                    string csvName = rewards;
                    StreamReader sr1 = File.OpenText(csvName);
                    string jsonWord1 = sr1.ReadToEnd();
                    string[] arr = jsonWord1.Split("\n");
                    sr1.Close();

                    long index = 0;//从第多少个数据开始转账，如果转账中断重新转账就需要这个

                    try
                    {
                        //根据转账成功的最后一个数据决定index
                        for (int i = 0; i < arr.Length - type - 1; i++)
                        {
                            string[] csvd = arr[i].Split(",");
                            if (csvd[0] == tranSuccessList[tranSuccessList.Count - 1]["address"])
                            {
                                index = i + 1;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        index = 0;
                    }
                    if (index >= (arr.Length - type - 1))
                    {
                        prog.Clear();
                        prog.Add("accomlish", "1");
                        prog.Add("errNum", errNum);
                        File.WriteAllText(progress, JsonHelper.ToJson(prog));
                        httpMessage.result = "转账完成。";
                        return;
                    }
                    while (index < (arr.Length - type - 1))
                    {

                        long times = (index + num) < (arr.Length - type - 1) ? (index + num) : (arr.Length - type - 1);
                        //得到csv文件的数据之后进行遍历，转账
                        for (long i = index; i < times; i++)
                        {

                            string[] csvd = arr[i].Split(",");
                            //代币转账
                            initHttpMessage_token(httpMessage, csvd, tokenAddress); //初始化httpmessage的信息 准备进行转账     注意这边填写代币地址
                            await OnTransfer_tokenAsync(httpMessage); //进行转账
                            //SAT转账
                            //initHttpMessage(httpMessage, csvd); //初始化httpmessage的信息 准备进行转账
                            //await OnTransferAsync(httpMessage); //进行转账
                            //转账失败 这样的话httpmessage的信息包括result，转账失败的原因
                            if (httpMessage.map.ContainsKey("result"))
                            {
                                int temp = 0;
                                string address = "";
                                string amount = "";
                                //可以给个文件然后将错误账号、金额、错误类型写进去未完成
                                if (httpMessage.result == "false")
                                {
                                    address = httpMessage.map["data"];
                                    amount = httpMessage.map["amount"].Replace("0000", "");
                                }
                                else
                                {
                                    address = httpMessage.map["1"];
                                    amount = httpMessage.map["2"];
                                }

                                Console.WriteLine(address);

                                errNum = (long.Parse(errNum) + 1).ToString();
                                prog["errNum"] = errNum;
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));
                                //foreach (var ii in errList)
                                //{
                                //    if (ii["address"] == address && ii["amount"] == (httpMessage.map["2"].Replace("\r", "")))
                                //    {
                                //        temp = 1;
                                //        break;
                                //    }
                                //}
                                if (temp == 0)
                                {
                                    Dictionary<string, string> res = new Dictionary<string, string>();
                                    res.Add("address", address);
                                    res.Add("amount", amount.Replace("\r", ""));
                                    res.Add("errtype", httpMessage.map["result"]);
                                    res.Add("time", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                    errList.Add(res);
                                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));
                                }
                                if (i == (times - 1))
                                {
                                    //转账完成将全局字典写进文件
                                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));
                                    //转账完成将完成标记写入
                                    prog.Clear();
                                    prog.Add("accomlish", "1");
                                    prog.Add("errNum", errNum);
                                    File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                    //转账完成将错误数据写入
                                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                    httpMessage.result = "转账完成。";

                                    index = times;
                                    Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                                }
                                continue;
                            }
                            //转账成功，将数据写入字典tranSuccessList中
                            Dictionary<string, string> tranSuccess = new Dictionary<string, string>();
                            tranSuccess.Add("address", csvd[0]);
                            tranSuccess.Add("amount", float.Parse(csvd[1]).ToString());
                            tranSuccess.Add("hash", httpMessage.map["hash"]);
                            tranSuccess.Add("accindex", httpMessage.map["accindex"]);
                            tranSuccessList.Add(tranSuccess);



                            //到了最后转账和数据写入完成，写入结束标记
                            if (i == (arr.Length - type - 2))
                            {
                                //转账完成将全局字典写进文件
                                string path = result1;//文件存放路径，保证文件存在。
                                StreamWriter sw = new StreamWriter(path, false);
                                sw.WriteLine(JsonHelper.ToJson(tranSuccessList));
                                sw.Close();

                                //转账完成将完成标记写入
                                prog.Clear();
                                prog.Add("accomlish", "1");
                                prog.Add("errNum", errNum);
                                File.WriteAllText(progress, JsonHelper.ToJson(prog));

                                //转账完成将错误数据写入
                                File.WriteAllText(errfile, JsonHelper.ToJson(errList));

                                httpMessage.result = "转账完成。";
                            }

                            if (i == (times - 1))
                            {
                                index = times;
                                Console.WriteLine("该批次转账完成,等待1.5分钟，进行验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                            }


                        }
                        List<Dictionary<string, string>> tranfalse = new List<Dictionary<string, string>>();
                        List<Dictionary<string, string>> tranundetermined = new List<Dictionary<string, string>>();
                        int status = 0;//0代表没问题  1代表有数据未查询出来
                        if (tranSuccessList.Count > 0)
                        {
                            Thread.Sleep(90 * 1000);//等待3分钟 之后判断后面的转账是否成功
                        }
                        Console.WriteLine("等待完毕，开始验证" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss"));
                        for (int i = 0; i < tranSuccessList.Count; i++)
                        {
                            initCheckHttpMessage(httpMessage, tranSuccessList[i]);
                            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                            //Console.WriteLine("验证信息结果"+result.result);//明天这边看一下结果然后看一下
                            if (result.result == "INVALID URL, set the correct url")
                            {
                                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                                if (result.result == "INVALID URL, set the correct url")
                                {
                                    status = 3;
                                    Console.WriteLine("网络或者ip问题");
                                    tranundetermined.Add(tranSuccessList[i]);
                                    continue;
                                }
                            }
                            if (result.result == "false")
                            {
                                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
                                if (result.result == "false")
                                {
                                    status = 1;
                                    tranfalse.Add(tranSuccessList[i]);
                                    continue;
                                    //break;
                                }

                            }
                            try
                            {
                                var res = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                                if (long.Parse(res["height"].ToString()) == 0)
                                {
                                    tranfalse.Add(tranSuccessList[i]);
                                }
                            }
                            catch (Exception e)
                            {
                                tranfalse.Add(tranSuccessList[i]);
                                Console.WriteLine("解析错误：" + e);
                            }
                        }
                        if (status == 1 || status == 3)
                        {
                            File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));//写入结果文件

                            File.WriteAllText(undeterminedfile, JsonHelper.ToJson(tranundetermined));
                            httpMessage.result = "该次转账未确定" + tranundetermined.Count + "个";
                            File.WriteAllText(tranfalsefile, JsonHelper.ToJson(tranfalse));
                            Console.WriteLine("该次转账共失败" + tranfalse.Count + "个");
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }

                        File.WriteAllText(tranfalsefile, JsonHelper.ToJson(tranfalse));
                        Console.WriteLine("该次转账共失败" + tranfalse.Count + "个");
                        tranSuccessList.Clear();
                        tranfalse.Clear();
                        httpMessage.result = "";
                        if (tranfalse.Count > 0)
                        {
                            string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                            Program.nonce = (int.Parse(nonce) + 1).ToString();
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);
                    Program.nonce = (int.Parse(nonce) + 1).ToString();
                    Console.WriteLine(e.Message);
                    File.WriteAllText(result1, JsonHelper.ToJson(tranSuccessList));//写入结果文件
                    File.WriteAllText(errfile, JsonHelper.ToJson(errList));//写入错误文件
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        private static void initCheckHttpMessage(HttpMessage httpMessage, Dictionary<string, string> tranMessage)
        {
            httpMessage.map.Clear();
            httpMessage.map.Add("accindex",tranMessage["accindex"]);
            httpMessage.map.Add("address", Wallet.ToAddress(Program.wallet.keys[0].publickey));
            httpMessage.map.Add("hash", tranMessage["hash"]);
            httpMessage.map.Add("amount", tranMessage["amount"]);
            httpMessage.map.Add("cmd", "block-by-tranhash");
        }

        private static float getOldSat(string address)
        {
            float oM = 0;
            Dictionary<string, Dictionary<string,string>> oData = new Dictionary<string, Dictionary<string, string>>();
            string txtName = "./oData.txt";
            StreamReader sr = File.OpenText(txtName);
            string jsonWord = sr.ReadToEnd();
            sr.Close();
            oData = JsonHelper.FromJson<Dictionary<string, Dictionary<string, string>>>(jsonWord);
            if (oData.ContainsKey(address))
            {
                oM = float.Parse(oData[address]["balance"]);
            }

            return oM;
        }

        private static void initHttpMessage(HttpMessage httpMessage, string[] csvd)
        {
            
            httpMessage.map.Clear();

            string input = "transfer " + csvd[0] + " " + csvd[1].Replace("\r","") + " 0";

            input = input.Replace("%20", " ");
            input = input.Replace("  ", " ");
            input = input.Replace("   ", " ");
            input = input.Replace("  ", " ");

            string[] array = input.Split(' ');

            for (int ii = 0; ii < array.Length; ii++)
            {
                string arrayValue = array[ii];
                httpMessage.map.Remove("" + ii);
                httpMessage.map.Add("" + ii, arrayValue);
            }

            httpMessage.map.Add("cmd", array[0]);
        }

        private static void initHttpMessage_token(HttpMessage httpMessage, string[] csvd,string tokenAddress)
        {
            httpMessage.map.Clear();

            string input = "tokentransfer " + csvd[0] + " " + csvd[1].Replace("\r", "") + " "+ tokenAddress;

            input = input.Replace("%20", " ");
            input = input.Replace("  ", " ");
            input = input.Replace("   ", " ");
            input = input.Replace("  ", " ");

            string[] array = input.Split(' ');

            for (int ii = 0; ii < array.Length; ii++)
            {
                string arrayValue = array[ii];
                httpMessage.map.Remove("" + ii);
                httpMessage.map.Add("" + ii, arrayValue);
            }

            httpMessage.map.Add("cmd", array[0]);
        }

        private static void initHttpMessage_token_new(HttpMessage httpMessage, string[] csvd, string tokenAddress)
        {
            httpMessage.map.Clear();

            string input = "tokentransfer " + csvd[0] + " " + csvd[1].Replace("\r", "") + " " + tokenAddress;

            input = input.Replace("%20", " ");
            input = input.Replace("  ", " ");
            input = input.Replace("   ", " ");
            input = input.Replace("  ", " ");

            string[] array = input.Split(' ');

            for (int ii = 0; ii < array.Length; ii++)
            {
                string arrayValue = array[ii];
                httpMessage.map.Remove("" + ii);
                httpMessage.map.Add("" + ii, arrayValue);
            }

            httpMessage.map.Add("cmd", array[0]);
            httpMessage.map.Add("nonce", csvd[2]);
            httpMessage.map.Add("timestamp", csvd[3]);
        }

        private static async System.Threading.Tasks.Task OnTransferAsync(HttpMessage httpMessage)
        {
            if (httpMessage.map.Count <= 3)
            {
                Console.WriteLine("transfer error example transfer addressOut amount fee");
                httpMessage.map.Add("result","-1");
                return;
            }
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                httpMessage.map.Add("result", "-2");
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["1"]))
            {
                httpMessage.result = "Please check addressOut";
                httpMessage.map.Add("result", "-3");
                return;
            }
            if (httpMessage.map["2"] == "0")
            {
                httpMessage.result = "please check your amount";
                httpMessage.map.Add("result", "-4");
                return;
            }
            if (httpMessage.map["1"]== Wallet.ToAddress(Program.wallet.keys[0].publickey))
            {
                httpMessage.result = "please check you address";
                httpMessage.map.Add("result", "-5");
                return;
            }

            TransferInfo(httpMessage, Program.ruleIP);//测试网或者新版本需要修改
            
            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

            if (result.result.Contains("true"))
            {
                Dictionary<string, object> accindex = new Dictionary<string, object>();//测试网或者新版本再增加
                accindex = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                httpMessage.map.Add("accindex", accindex["accindex"].ToString());
                Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                httpMessage.result = result.result + " " + httpMessage.map["hash"];
                
                Console.WriteLine(Program.nonce);
            }
            else
            {
                httpMessage.result = "false";
                httpMessage.map.Add("result", "-6");
            }
        }

        private static async System.Threading.Tasks.Task OnTransfer_tokenAsync(HttpMessage httpMessage)
        {
            if (httpMessage.map.Count <= 4)
            {
                Console.WriteLine("tokentransfer error example tokentransfer addressOut amount conAddress");
                return;
            }
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["1"]))
            {
                httpMessage.result = "Please check addressOut";
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["3"]))
            {
                httpMessage.result = "Please check conAddress";
                return;
            }
            TransferInfo_Token(httpMessage, Program.ruleIP);//测试网或者新版本需要修改
            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
            if(result.result == "INVALID URL, set the correct url")
                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

            if (result.result.Contains("true"))
            {
                Dictionary<string, object> accindex = new Dictionary<string, object>();//测试网或者新版本再增加
                accindex = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                httpMessage.map.Add("accindex", accindex["accindex"].ToString());
                Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                httpMessage.result = result.result + " " + httpMessage.map["hash"];

                Console.WriteLine(Program.nonce);
            }
            else
            {
                Console.WriteLine("错误原因："+result.result);
                httpMessage.result = "false";
                httpMessage.map.Add("result", "-6");
            }
        }
        private static async System.Threading.Tasks.Task OnTransfer_tokenAsync_new(HttpMessage httpMessage)
        {
            if (httpMessage.map.Count <= 4)
            {
                Console.WriteLine("tokentransfer error example tokentransfer addressOut amount conAddress");
                return;
            }
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["1"]))
            {
                httpMessage.result = "Please check addressOut";
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["3"]))
            {
                httpMessage.result = "Please check conAddress";
                return;
            }
            TransferInfo_Token_new(httpMessage, Program.ruleIP);//测试网或者新版本需要修改
            HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
            if (result.result == "INVALID URL, set the correct url")
                result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

            if (result.result.Contains("true"))
            {
                Dictionary<string, object> accindex = new Dictionary<string, object>();//测试网或者新版本再增加
                accindex = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                httpMessage.map.Add("accindex", accindex["accindex"].ToString());
                Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                httpMessage.result = result.result + " " + httpMessage.map["hash"];

                Console.WriteLine(Program.nonce);
            }
            else
            {
                Console.WriteLine("错误原因：" + result.result);
                httpMessage.result = "false";
                httpMessage.map.Add("result", "-6");
            }
        }

        private static async System.Threading.Tasks.Task OnTransferTestIPsAsync(string ip,HttpMessage httpMessage)
        {
            if (httpMessage.map.Count <= 3)
            {
                Console.WriteLine("transfer error example transfer addressOut amount fee");
                httpMessage.map.Add("result", "-1");
                return;
            }
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                httpMessage.map.Add("result", "-2");
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["1"]))
            {
                httpMessage.result = "Please check addressOut";
                httpMessage.map.Add("result", "-3");
                return;
            }
            if (httpMessage.map["2"] == "0")
            {
                httpMessage.result = "please check your amount";
                httpMessage.map.Add("result", "-4");
                return;
            }
            if (httpMessage.map["1"] == Wallet.ToAddress(Program.wallet.keys[0].publickey))
            {
                httpMessage.result = "please check you address";
                httpMessage.map.Add("result", "-5");
                return;
            }

            TransferInfoTestIPs(httpMessage, ip);//测试网或者新版本需要修改

            HttpMessage result = await ComponentNetworkHttp.QueryCommand(ip + $"/{httpMessage.map["cmd"]}", httpMessage);

            if (result.result.Contains("true"))
            {
                Dictionary<string, object> accindex = new Dictionary<string, object>();//测试网或者新版本再增加
                accindex = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                httpMessage.map.Add("accindex", accindex["accindex"].ToString());
                Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                httpMessage.result = result.result + " " + httpMessage.map["hash"];

                //Console.WriteLine(Program.nonce);
            }
            else
            {
                httpMessage.result = "false";
                httpMessage.map.Add("result", "-6");
            }
        }
        private static async System.Threading.Tasks.Task OnTransferTestIPsAsync2(string ip, HttpMessage httpMessage)
        {
            if (httpMessage.map.Count <= 3)
            {
                Console.WriteLine("transfer error example transfer addressOut amount fee");
                httpMessage.map.Add("result", "-1");
                return;
            }
            if (Program.wallet.keys.Count == 0)
            {
                httpMessage.result = "Please set the wallet first";
                httpMessage.map.Add("result", "-2");
                return;
            }
            if (!Wallet.CheckAddress(httpMessage.map["1"]))
            {
                httpMessage.result = "Please check addressOut";
                httpMessage.map.Add("result", "-3");
                return;
            }
            if (httpMessage.map["2"] == "0")
            {
                httpMessage.result = "please check your amount";
                httpMessage.map.Add("result", "-4");
                return;
            }
            if (httpMessage.map["1"] == Wallet.ToAddress(Program.wallet.keys[0].publickey))
            {
                httpMessage.result = "please check you address";
                httpMessage.map.Add("result", "-5");
                return;
            }

            TransferInfoTestIPs2(httpMessage, ip);//测试网或者新版本需要修改

            HttpMessage result = await ComponentNetworkHttp.QueryCommand(ip + $"/{httpMessage.map["cmd"]}", httpMessage);

            if (result.result.Contains("true"))
            {
                Dictionary<string, object> accindex = new Dictionary<string, object>();//测试网或者新版本再增加
                accindex = JsonHelper.FromJson<Dictionary<string, object>>(result.result);
                httpMessage.map.Add("accindex", accindex["accindex"].ToString());
                Program.nonce = (int.Parse(Program.nonce) + 1).ToString();
                httpMessage.result = result.result + " " + httpMessage.map["hash"];

                //Console.WriteLine(Program.nonce);
            }
            else
            {
                httpMessage.result = "false";
                httpMessage.map.Add("result", "-6");
            }
        }

        private static async System.Threading.Tasks.Task<string> GetHeightAsync()
        {
            Dictionary<string, object> latestBlockHeight = new Dictionary<string, object>();
            latestBlockHeight.Add("success", true);
            latestBlockHeight.Add("message", "successful operation");
            latestBlockHeight.Add("height", "");
            HttpMessage temp = new HttpMessage();
            temp.map = new Dictionary<string, string>();
            temp.map.Add("cmd", "latest-block-height");
            temp = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{temp.map["cmd"]}", temp);
            var temp1 = JsonHelper.FromJson<Dictionary<string, object>>(temp.result);
            return (string)temp1["height"];
        }

        private static string AddKeyBag(string randomseed, Dictionary<string, WalletKey> keyBag)
        {
            WalletKey walletKey = new WalletKey();
            ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, randomseed.HexToBytes());
            string address = Wallet.ToAddress(walletKey.publickey);
            walletKey.random = randomseed.HexToBytes();
            if (Program.keyBag.Count > 0)
            {
                if (keyBag.ContainsKey(address))
                {
                    return "The address already exists!";
                }
            }
            else
            {
                if (!Program.keyBag.ContainsKey(address)) keyBag.Add(address, walletKey);
            }
            
           
            return address;
        }

        private static void TransferInfo(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp = (TimeHelper.Now()).ToString();
            string cmd = "transfer";//1
            string type = cmd;//2
            string nonce = Program.nonce;
            string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);//3
            string addressOut = httpMessage.map["1"];//4
            //string amount = (double.Parse(httpMessage.map["2"]) * 10000) + "";//5
            string amount = (httpMessage.map["2"]) + "";//5 测试网或者新版本
            string data = "";//6
            string fee = "";
            string depend = "";//7
            string remarks = "";
            string str_extend = "";
            //string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}";
            string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
            string hash = CryptoHelper.Sha256(hashdata);//8
            string sign = GetSign(hash).ToLower();//9
            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("fee", fee);
            httpMessage.map.Add("timestamp", timestamp);
            httpMessage.map.Add("remarks", remarks);
            File.AppendAllText("./urlData.csv", addressOut+","+amount+","+hash+"\n");
            //File.AppendAllText("./TestIPs"+ ruleIP+ ".csv", addressOut + "," + amount + "," + hash + "\n");
        }

        private static void TransferInfo_Token(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp = (TimeHelper.Now()).ToString();

            string cmd = "transfer";//1
            string type = "contract";//2
            string nonce = Program.nonce; 

            string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);//3
            string addressOut = httpMessage.map["3"];//4
            string amountm = (float.Parse(httpMessage.map["2"])).ToString();//5
            string data = "transfer(\"" + httpMessage.map["1"] + "\"," + "\"" + amountm + "\")";//6
            string amount = "";
            string depend = "";//7
            string remarks = "Token_Tran";
            string str_extend = "";
            string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
            string hash = CryptoHelper.Sha256(hashdata);//8
            string sign = GetSign(hash).ToLower();//9

            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("timestamp", timestamp);
            httpMessage.map.Add("remarks", remarks);
        }
        private static void TransferInfo_Token_new(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp = httpMessage.map["timestamp"];//这个也要固定

            string cmd = "transfer";//1
            string type = "contract";//2
            string nonce = httpMessage.map["nonce"]; //----------这个要固定

            string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);//3
            string addressOut = httpMessage.map["3"];//4
            string amountm = (float.Parse(httpMessage.map["2"])).ToString();//5
            string data = "transfer(\"" + httpMessage.map["1"] + "\"," + "\"" + amountm + "\")";//6
            string amount = "";
            string depend = "";//7
            string remarks = "Token_Tran";
            string str_extend = "";
            string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
            string hash = CryptoHelper.Sha256(hashdata);//8
            string sign = GetSign(hash).ToLower();//9

            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("timestamp", timestamp);
            httpMessage.map.Add("remarks", remarks);
        }

        private static void TransferInfoTestIPs(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp = (TimeHelper.Now()).ToString();
            string cmd = "transfer";//1
            string type = cmd;//2
            string nonce = Program.nonce;
            string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);//3
            string addressOut = httpMessage.map["1"];//4
            //string amount = (double.Parse(httpMessage.map["2"]) * 10000) + "";//5
            string amount = (httpMessage.map["2"]) + "";//5 测试网或者新版本
            string data = "";//6
            string fee = (httpMessage.map.Count == 5 ? httpMessage.map["3"] : "0");
            string depend = "";//7
            string remarks = "";
            string str_extend = "";
            //string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}";
            string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
            string hash = CryptoHelper.Sha256(hashdata);//8
            string sign = GetSign(hash).ToLower();//9
            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("fee", fee);
            httpMessage.map.Add("timestamp", timestamp);
            httpMessage.map.Add("remarks", remarks);
            //File.AppendAllText("./urlData.csv", addressOut + "," + amount + "," + hash + "\n");
            File.AppendAllText("./TestIPs" + ruleIP.Replace("https://", "").Replace("http://", "").Replace(":5000", "").Replace(".", "") + ".csv", addressOut + "," + amount + "," + hash + "\n");
        }

        private static void TransferInfoTestIPs2(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp = (TimeHelper.Now()).ToString();
            string cmd = "transfer";//1
            string type = cmd;//2
            string nonce = Program.nonce;
            string addressIn = Wallet.ToAddress(Program.wallet.keys[0].publickey);//3
            string addressOut = httpMessage.map["1"];//4
            //string amount = (double.Parse(httpMessage.map["2"]) * 10000) + "";//5
            string amount = (httpMessage.map["2"]) + "";//5 测试网或者新版本
            string data = "";//6
            string fee = (httpMessage.map.Count == 5 ? httpMessage.map["3"] : "0");
            string depend = "";//7
            string remarks = "";
            string str_extend = "";
            //string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}";
            string hashdata = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";//新版本
            string hash = CryptoHelper.Sha256(hashdata);//8
            string sign = GetSign(hash).ToLower();//9
            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("fee", fee);
            httpMessage.map.Add("timestamp", timestamp);
            httpMessage.map.Add("remarks", remarks);
            Console.WriteLine(hash);
            //File.AppendAllText("./urlData.csv", addressOut + "," + amount + "," + hash + "\n");
            //File.AppendAllText("./TestIPs" + ruleIP.Replace("https://", "").Replace("http://", "").Replace(":5000", "").Replace(".", "") + ".csv", addressOut + "," + amount + "," + hash + "\n");
            File.AppendAllText("./TestIPs" + "explore" + ".csv", addressOut + "," + amount + "," + hash + "\n");
        }

        private static string GetSign(string hash)
        {
            string address = Wallet.ToAddress(Program.wallet.keys[0].publickey);
            string sign = Wallet.Sign(hash.HexToBytes(), Program.wallet.keys[0]).ToHex();
            return sign;
        }

        private static async System.Threading.Tasks.Task<string> GetNonceAsync(string address, HttpMessage httpMessage, string ruleIP)
        {
            httpMessage.map["cmd"] = "getnonce";
            httpMessage.map["address"] = address;
            HttpMessage result = await ComponentNetworkHttp.QueryCommand(ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);
            if (result.result == "INVALID URL, set the correct url" || result.result == "false") return result.result;
            Dictionary<string, string> nonce = JsonHelper.FromJson<Dictionary<string, string>>(result.result);
            string nonc = nonce["nonce"];
            return nonc;
        }

        private static bool GetParam(HttpMessage httpMessage, string key1, string key2, out string value)
        {
            if (!httpMessage.map.TryGetValue(key1, out value))
            {
                if (!httpMessage.map.TryGetValue(key2, out value))
                    return false;
            }
            return true;
        }
        static public byte[] Seek()
        {
            byte[] seed = new byte[32];
            ed25519.ed25519_create_seed(seed);
            return seed;
        }
        private static void OnCreat(HttpMessage httpMessage)
        {
            try
            {
                Console.Write("please input your password:");
                string passwd = Console.ReadLine();
                Wallet wallet = new Wallet();
                wallet = wallet.NewWallet(passwd);
                if (httpMessage.map.Count == 3)
                {
                    wallet.walletFile = httpMessage.map["1"] + "/wallet.json";
                }
                else
                {
                    wallet.walletFile = "./wallet.json";
                }
                wallet.SaveWallet();
                if (wallet.keys.Count > 0)
                {
                    httpMessage.result = JsonHelper.ToJson(wallet.keys[0].ToAddress());
                    return;
                }
                httpMessage.result = "create account error";
            }
            catch (Exception e)
            {
                httpMessage.result = "path error";

            }
            
        }
        private static void OnHelp(HttpMessage httpMessage)
        {
            Dictionary<string, string> c = new Dictionary<string, string>();
            c.Add("importkey privatekey", "Users can import their private keys into nodeshell to recover their wallets");
            c.Add("createwallet path", "The path parameter is the wallet path, which can be used to create a wallet file");
            c.Add("createkey", "Public and private key pairs can be created");
            c.Add("transfercount address", "Returns all transactions at an address");
            c.Add("getlastblock index", "Index: the page number of the most recently generated block, and returns the most recently generated main block");
            c.Add("mempool", "Returns unprocessed transactions in the memory pool");
            c.Add("search hash / address", "Search main block information, transaction information or address transaction information");
            c.Add("miner", "Information about miners mining");
            c.Add("node", "Return the valid node information that is connecting in smartx P2P network");
            c.Add("beruler", "With a certain number of SAT coins, you can send a transaction through this command to become a POS verification node");
            c.Add("rules", "Returns the current POS verification node information of smartx network");
            c.Add("stats", "Current network statistics");
            c.Add("account address", "Return the current address, including balance information");
            c.Add("transfer addressOut amount fee", "Addressout: transfer out address ,amount: transfer out amount ,fee: service charge and return the transfer result");
            c.Add("exportkey path", "Export default wallet to path");
            c.Add("getprivatekey", "Get the current default wallet private key");
            c.Add("closewallet", "Cancel current Wallet");
            c.Add("list", "List all wallets in the system");
            c.Add("setwallet address", "Set current Wallet");
            c.Add("openwallet path", "Open and set the current Wallet");
            c.Add("help", "Display executable commands");
            c.Add("clear", "Clear current  screen");
            c.Add("showip", "Displays the IP address of the current computer connection");
            httpMessage.result = JsonHelper.ToJson(c);
        }

        private static async System.Threading.Tasks.Task OnCheckTokenAsync(HttpMessage httpMessage)
        {
            await InitTokenInfoAsync(httpMessage);
            Dictionary<string, string> token = new Dictionary<string, string>();
            File.Delete("./token.csv");
            for (int i = 1; i < httpMessage.map.Count; i++)
            {
                try
                {
                    string[] arr = httpMessage.map[(i + 1).ToString()].Split(":");
                    token.Add(arr[2],arr[0]);
                    File.AppendAllText("./token.csv", arr[0] + "," + arr[2] + "\n");
                }
                catch (Exception e)
                {
                    Console.WriteLine(httpMessage.map[(i + 1).ToString()]);
                }
            }
            Console.WriteLine("导出完成。");
            File.Delete("./token奖励结果.csv");
            string tokens = File.ReadAllText("./token.csv");
            string[] arrToken = tokens.Replace("\r", "").Split("\n");
            Dictionary<string, string> rewardsToken = new Dictionary<string, string>();
            string tokenrewardss = File.ReadAllText("./3000合约奖励.csv");
            string[] rewards = tokenrewardss.Replace("\r", "").Split("\n");
            //得到他的所有的合约地址和珊瑚地址
            for (int i = 0; i < rewards.Length-1; i++)
            {
                string[] arr = rewards[i].Replace(" ","").Split(",");
                try
                {
                    rewardsToken.Add(arr[1], arr[0]);
                }
                catch (Exception e)
                {
                    Console.WriteLine(arr[1]);
                }
            }


            //得到所有的代币自己的地址
            for (int i = 0; i < arrToken.Length - 1; i++)
            {
                string[] arr = arrToken[i].Split(",");
                await InitTranInfo(httpMessage, arr[1]);//得到自己的所有交易
                if (httpMessage.result.Contains(arr[1]))
                {
                    List<Dictionary<string, string>> list1 = new List<Dictionary<string, string>>();
                    list1 = JsonHelper.FromJson<List<Dictionary<string, string>>>(httpMessage.result);
                    for (int ii = 0; ii < list1.Count; ii++)
                    {
                        if (rewardsToken.ContainsKey(list1[ii]["addressIn"]))
                        {
                            File.AppendAllText("./token奖励结果.csv", rewardsToken[list1[ii]["addressIn"]] + ",3000" + "\n");
                            rewardsToken.Remove(list1[ii]["addressIn"]);
                            break;
                        }
                    }
                }
            }
            File.Delete("./token未找到.csv");


            foreach (KeyValuePair<string, string> kvp in rewardsToken)

           {

                Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

            }

            //Dictionary<string, string>.ValueCollection keyCol = rewardsToken.Values;
            //foreach (string key in keyCol)
            //{
            //    Console.WriteLine("Key = {0}", key);
            //}

            Console.WriteLine("token奖励导出完成");
            httpMessage.result = "";

        }

        private static async System.Threading.Tasks.Task InitTokenInfoAsync(HttpMessage httpMessage)
        {
            //http://152.32.186.159:5000/?v=1.0.0&cmd=getproperty&address=fXDMHPEaxv6udVLBuBmjLKPscbNskTBXd
            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", "getproperty");
            httpMessage.map.Add("address", "ibCQqKjqfP9AnYZVVeMQq6CPBiB2UazKt");
            HttpMessage result = await ComponentNetworkHttp.QueryCommand("http://152.32.186.159:5000" + $"/{httpMessage.map["cmd"]}", httpMessage);
            httpMessage.map =  JsonHelper.FromJson<Dictionary<string,string>>(result.result);
        }

        private static async System.Threading.Tasks.Task InitTranInfo(HttpMessage httpMessage,string address)
        {
            //http://152.32.186.159:5000/?v=1.0.0&cmd=gettransfers&address=ibCQqKjqfP9AnYZVVeMQq6CPBiB2UazKt&index=0&token=npeWP8FRqR1GtayV8iv96URcyNBr7UXqt
            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", "gettransfers");
            httpMessage.map.Add("address", "ibCQqKjqfP9AnYZVVeMQq6CPBiB2UazKt");
            httpMessage.map.Add("index", "0");
            httpMessage.map.Add("token",address);
            HttpMessage result = await ComponentNetworkHttp.QueryCommand("http://152.32.186.159:5000" + $"/{httpMessage.map["cmd"]}", httpMessage);
            httpMessage.result = result.result;
        }

        public static void CustomAddressTool(object data)
        {
            ThreadData This = data as ThreadData;
            string name = This.addressHead;
            string threadNum = This.threadNum;
            long times = 0;
            while (true)
            {
                WalletKey walletKey = new WalletKey();
                string input = name;
                walletKey.random = CryptoHelper.Sha256(Seek().ToHexString() + "#" + input).HexToBytes();
                ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, walletKey.random);
                string walletAddress = Wallet.ToAddress(walletKey.publickey);
                //File.AppendAllText("./" +"AllAddress" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n"); //最好单线程保存所有的地址
                if (walletAddress.IndexOf(name) ==0 )
                {
                    Console.WriteLine(threadNum+"经过" +times+"次努力计算终于得到您想要的地址~~~");
                    File.AppendAllText("./" + name + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                    orderAddress = true;
                    break;
                }
                if (walletAddress.ToLower().IndexOf((name.ToLower())) == 0)
                {
                    File.AppendAllText("./" + name.ToLower() + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }
                if (walletAddress.IndexOf("WuFeng") == 0)
                {
                    File.AppendAllText("./" + "WuFeng" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }
                if (walletAddress.ToLower().IndexOf("wufeng") == 0)
                {
                    File.AppendAllText("./" + "wufeng" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }
                
                if (walletAddress.IndexOf("SATLiu") == 0)
                {
                    File.AppendAllText("./" + "SATLiu" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }
                if (walletAddress.ToLower().IndexOf("jayrLiu") == 0)
                {
                    File.AppendAllText("./" + "jayrLiu" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }
                if (walletAddress.ToLower().IndexOf("LiuFengLin") == 0)
                {
                    File.AppendAllText("./" + "LiuFengLin" + ".csv", $"{walletAddress},{walletKey.random.ToHexString()}\n");
                }


                times++;
                if (times % 1000000 == 0)
                {
                    Console.WriteLine(threadNum+"经过" + times + "次努力计算还是没有得到您想要的地址~~~");
                }
                if (orderAddress)
                {
                    break;
                }
            }
        }

        public static string httpMethod(string p_url, int timeout)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(p_url);
            request.Timeout = timeout;
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string res = reader.ReadToEnd();
            request.Abort();
            stream.Dispose();
            reader.Dispose();
            response.Dispose();
            return res;
        }

        public class ThreadData
        {
            public string addressHead;
            public string threadNum;
        }

        public class ThreadData2
        {
            public string ip;
            public int time;
            public string threadNum;
        }
    }
}
